[Chartjs]-How to show tooltip on legend item in chart.js

6👍

This is quite straightforward using the onHover callback.

Below is a snippet with a crude implementation but it is illustrative of the technique required.

let hovering = false,
  tooltip = document.getElementById("tooltip"),
  tooltips = ["such tooltip", "blah blah"],
  mychart = new Chart(document.getElementById("chart"), {
    type: "bar",
    data: {
      labels: ['a', 'b', 'c'],
      datasets: [{
        label: "series 1",
        data: [1, 2, 3]
      }, {
        label: "series 2",
        data: [1, 2, 3]
      }]
    },
    options: {
      legend: {
        onHover: function(event, legendItem) {
          if (hovering) {
            return;
          }
          hovering = true;
          tooltip.innerHTML = tooltips[legendItem.datasetIndex];
          tooltip.style.left = event.x + "px";
          tooltip.style.top = event.y + "px";
        },
        onLeave: function() {
          hovering = false;
          tooltip.innerHTML = "";
        }
      }
    }
  });
#tooltip {
  background-color: #000;
  color: #fff;
  position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<canvas id="chart"></canvas>
<div id="tooltip"></div>

Leave a comment