chart.jschart.js3

Chart.js How To Show Tooltip on Legend Hover


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.


Solution

  • 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>