Chartjs-ChartJS display tooltip at maximum/minimum value

0๐Ÿ‘

โœ…

I found an answer to this option and posted it in the linked jsfiddle. I had to add a plugin that would display all labels. That one then dynamically decided whether to show this tooltip or not.

Chart.pluginService.register
  beforeRender: (chart) ->
    if chart.config.options.showAllTooltips
      # create an array of tooltips
      # we can't use the chart tooltip because there is only one tooltip per chart
      chart.pluginTooltips = []
      chart.config.data.datasets.forEach (dataset, i) ->
        min = _.min(dataset.data, (d)-> d)
        max = _.max(dataset.data, (d)-> d)
        minShown = false
        maxShown = false
        chart.getDatasetMeta(i).data.forEach (sector, j) ->
          isMax = dataset.data[j] == max
          isMin = dataset.data[j] == min
          # only show the min and the max once. we can have duplicates min/maxes
          if isMax && !maxShown || isMin && !minShown
            minShown = true if isMin
            maxShown = true if isMax
            tooltip = new (Chart.Tooltip)({
              _chart: chart.chart
              _chartInstance: chart
              _data: chart.data
              _options: chart.options.tooltips
              _active: [ sector ]
            }, chart)
            chart.pluginTooltips.push(tooltip)
          return
        return
      # turn off normal tooltips
      chart.options.tooltips.enabled = false
    return
  afterDraw: (chart, easing) ->
    if chart.config.options.showAllTooltips
      # we don't want the permanent tooltips to animate, so don't do anything till the animation runs atleast once
      if !chart.allTooltipsOnce
        if easing != 1
          return
        chart.allTooltipsOnce = true
      # turn on tooltips
      chart.options.tooltips.enabled = true
      Chart.helpers.each chart.pluginTooltips, (tooltip) ->
        tooltip.initialize()
        tooltip.update()
        # we don't actually need this since we are not animating tooltips
        tooltip.pivot()
        tooltip.transition(easing).draw()
        return
      chart.options.tooltips.enabled = false
    return

Leave a comment