Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show tooltip on legend item in chart.js

I'm trying to find the way how to show tooltip when user hovers the legend in Chart.js library. I have found several issues but none of them was solved.

https://github.com/chartjs/Chart.js/issues/4023 Chart.js - show tooltip when hovering on legend

Does anybody have any idea how to manage that? Thank you

like image 987
Michal S. Avatar asked Oct 18 '25 13:10

Michal S.


1 Answers

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>
like image 69
timclutton Avatar answered Oct 21 '25 01:10

timclutton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!