How to detect when tooltip closes in chart.js?

Member

by rollin , in category: Javascript , 10 months ago

How to detect when tooltip closes in chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , 5 months ago

@rollin 

Chart.js does not have a built-in way to detect when a tooltip closes. One workaround is to listen for mouse events on the chart canvas element and use the tooltip callbacks to track when the tooltip is being shown or hidden.


Here's an example of how you can do this:

  1. Add event listeners for mouseenter and mouseleave events on the chart canvas element:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const chartCanvas = document.getElementById('myChart').getContext('2d');

chartCanvas.canvas.addEventListener('mouseenter', function(e) {
  // Tooltip is being shown
  console.log('Tooltip shown');
});

chartCanvas.canvas.addEventListener('mouseleave', function(e) {
  // Tooltip is being hidden
  console.log('Tooltip hidden');
});


  1. Use the tooltip callbacks to track when the tooltip is being shown or hidden:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const myChart = new Chart(chartCanvas, {
  type: 'line',
  data: {
    labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
    datasets: [{
      label: 'My Dataset',
      data: [10, 20, 30, 40, 50, 60, 70]
    }]
  },
  options: {
    tooltips: {
      enabled: false,
      custom: function(tooltipModel) {
        if (tooltipModel.opacity === 0) {
          // Tooltip is being hidden
          console.log('Tooltip hidden');
        } else {
          // Tooltip is being shown
          console.log('Tooltip shown');
        }
      }
    }
  }
});


By using these event listeners and tooltip callbacks, you can track when the tooltip is being shown or hidden in Chart.js.