Chartjs Show tooltip automatically

1👍

This can be done with the Plugin Core API in the afterDatasetUpdate hook as follows:

afterDatasetUpdate: chart => {
  if (!chart.tooltip.getActiveElements().length) {
    chart.tooltip.setActiveElements([{
      datasetIndex: 0,
      index: chart.data.datasets[0].data.length - 1
    }]);
    chart.update();
  }
} 

Please take a look at the runnable code snippet below and see how it works.

new Chart('myChart', {
  type: 'line',
  plugins: [{
    afterDatasetUpdate: chart => {
      if (!chart.tooltip.getActiveElements().length) {
        chart.tooltip.setActiveElements([{
          datasetIndex: 0,
          index: chart.data.datasets[0].data.length - 1
        }]);
        chart.update();
      }
    }
  }],
  data: {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [{
      label: '# of Events',
      data: [65, 59, 80, 81, 56, 55, 68],
      borderColor: '#a00'
    }]
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
<canvas id="myChart" width="400" height="95"></canvas>

👍:0

thanks – it is exactly, what I am looking for!
The snippet in your answer works with visible tooltip on the last data point.
When I try it in test.html in my browser (I tested firefox, edge,chrome) the tooltip is not visible.
Where is the mistake in my test.html?

<!DOCTYPE html>
<html>

<body>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
  <canvas id="myChart" width="400" height="95"></canvas>
  <script type="text/javascript">
    new Chart('myChart', {
      type: 'line',
      plugins: [{
        afterDatasetUpdate: chart => {
          if (!chart.tooltip.getActiveElements().length) {
            chart.tooltip.setActiveElements([{
              datasetIndex: 0,
              index: chart.data.datasets[0].data.length - 1
            }]);
            chart.update();
          }
        }
      }],
      data: {
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [{
          label: '# of Events',
          data: [65, 59, 80, 20, 81, 56, 55, 68],
          borderColor: '#a00'
        }]
      }
    });
  </script>
</body>
</html>

that is my test:

https://www.zebrafell.de/test.html

Leave a comment