Chartjs-Chart.js How To Show Tooltip on Legend Hover

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>

Leave a comment