0

I am trying to show a tooltip with the graph data (label and y value) when the corresponding legend key is hovered over. I can only find solutions which work for older versions of Chart.js, I am using 3.8.0.

Apostolos
  • 10,033
  • 5
  • 24
  • 39
  • You can use programatic event triggers together with a legend callback: https://www.chartjs.org/docs/master/samples/advanced/programmatic-events.html – LeeLenalee Jun 28 '22 at 17:26

1 Answers1

0

This can be done by defining a options.plugins.legend.onHover function as follows:

legend: {
  onHover: (evt, legendItem) => {
    const activeElement = {
      datasetIndex: 0,
      index: legendItem.index
    };
    chart.tooltip.setActiveElements([activeElement]);
    chart.update();
  }
}

Please take a look at the runnable code below and see how it works.

const chart = new Chart('chart', {
  type: 'doughnut',
  data: {
    labels: ['One', 'Two', 'Three'],
    datasets: [{
      data: [4, 5, 3],
      backgroundColor: ['rgba(255, 99, 132, 0.2)', 'rgba(255, 159, 64, 0.2)', 'rgba(54, 162, 235, 0.2)'],
      borderColor: ['rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(54, 162, 235)'],
      hoverBackgroundColor: ['rgba(255, 99, 132, 0.4)', 'rgba(255, 159, 64, 0.4)', 'rgba(54, 162, 235, 0.4)'],
      borderWidth: 1,
      hoverBorderWidth: 3
    }]
  },
  options: {
    plugins: {
      legend: {
        onHover: (evt, legendItem) => {
          const activeElement = {
            datasetIndex: 0,
            index: legendItem.index
          };
          chart.setActiveElements([activeElement]); // to also show thick border
          chart.tooltip.setActiveElements([activeElement]);
          chart.update();
        }
      }
    }
  }
});
canvas {
  max-height: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js"></script>
<canvas id="chart"></canvas>
uminder
  • 23,831
  • 5
  • 37
  • 72
  • This works perfectly, thank you so much! I was getting caught up in some old docs with using metadata functions and it just wasn't retrieving the correct data to display. – VioletSkies Jul 01 '22 at 09:13
  • getting a TypeError: Cannot read properties of undefined (reading 'x') error here when hovering over a legend. Not sure why. – Dave Driesmans Aug 22 '23 at 08:34