[Chartjs]-ChartJS multiple tooltip callbacks not working

1👍

Your use case is the given example for tooltip callbacks on the Chart.js samples page with the following code:

// Use the footer callback to display the sum of the items showing in the tooltip
footer: function(tooltipItems, data) {
  var sum = 0;

  tooltipItems.forEach(function(tooltipItem) {
    sum += data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
  });
  return 'Sum: ' + sum;
}

Editing your snippet as per the above example seems to yield the result you want, although you probably want it formatted to match the rest of your tooltip:

new Chart(document.getElementById("line-chart"), {
  type: 'line',
  data: {
    labels: [2018, 2019, 2020],
    datasets: [{
      data: [1.09, 1.48, 2.48],
      label: "ABC",
      borderColor: "#3e95cd",
      fill: false
    }, {
      data: [0.63, 0.81, 0.95],
      label: "DEF",
      borderColor: "#8e5ea2",
      fill: false
    }, {
      data: [0.17, 0.17, 0.18],
      label: "GHI",
      borderColor: "#3cba9f",
      fill: false
    }]
  },
  options: {
    title: {
      display: true,
      text: 'Past 2FY + Current FY Estimate, US$ millions'
    },
    tooltips: {
      mode: 'index',
      callbacks: {
        label: function(tooltipItem, data) {
          if (tooltipItem.index > 0) {
            var previousdata = tooltipItem.index - 1;
            var growth = ", YoY: " + ((data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index] / data.datasets[tooltipItem.datasetIndex].data[previousdata] * 100) - 100).toFixed(1) + "%";
          } else {
            var growth = '';
          };

          return data.datasets[tooltipItem.datasetIndex].label + ': $' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index] + growth;

        },
        footer: function(tooltipItems, data) {
          var sum = 0;

          tooltipItems.forEach(function(tooltipItem) {
            sum += data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
          });
          return 'Sum: ' + sum;
        }
      }
    }
  }
});
<canvas id="line-chart"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>

Leave a comment