Chartjs-How to get access to Chart instance related to current tooltip callback in Chart.js

0๐Ÿ‘

โœ…

I think the best approach to solving your problem is to actually use custom tooltips instead of attempting a plugin. Here is a working solution that I modified from one of the chart.js sample pages in their repo.

First define a container for the custom tooltip in yout HTML.

<div id="chartjs-tooltip"></div>

Then use the below custom tooltip function. You might have to tweak the centerX calculation for your needs. This function basically calculates the percentage value of the currently active slice (by dividing the datapoint by the total value of datapoints), places it in the custom tooltip div, and positions the div in the center of the doughnut.

Chart.defaults.global.tooltips.custom = function(tooltip) {
  // Tooltip Element
  var tooltipEl = document.getElementById('chartjs-tooltip');

  // Hide if no tooltip
  if (tooltip.opacity === 0) {
    tooltipEl.style.opacity = 0;
    return;
  }

  // Set Text
  if (tooltip.body) {
    var total = 0;

    // get the value of the datapoint
    var value = this._data.datasets[tooltip.dataPoints[0].datasetIndex].data[tooltip.dataPoints[0].index].toLocaleString();

    // calculate value of all datapoints
    this._data.datasets[tooltip.dataPoints[0].datasetIndex].data.forEach(function(e) {
      total += e;
    });

    // calculate percentage and set tooltip value
    tooltipEl.innerHTML = '<h1>' + (value / total * 100) + '%</h1>';
  }

  // calculate position of tooltip
  var centerX = (this._chartInstance.chartArea.left + this._chartInstance.chartArea.right) / 2;
  var centerY = ((this._chartInstance.chartArea.top + this._chartInstance.chartArea.bottom) / 2);

  // Display, position, and set styles for font
  tooltipEl.style.opacity = 1;
  tooltipEl.style.left = centerX + 'px';
  tooltipEl.style.top = centerY + 'px';
  tooltipEl.style.fontFamily = tooltip._fontFamily;
  tooltipEl.style.fontSize = tooltip.fontSize;
  tooltipEl.style.fontStyle = tooltip._fontStyle;
  tooltipEl.style.padding = tooltip.yPadding + 'px ' + tooltip.xPadding + 'px';
};

Here is the full end-to-end working example via codepen:

Chart.js Doughnut Center Percentage

Leave a comment