chart.js

chartjs Show tooltip automatically


I create charts for weather. I want to show automatically the tooltip on the last datapoint, when the chart is created. When the mouse is moved to another datapoint, the tootip should move to the new datapoint of the mouse or vanish if the mouse is outside.

https://www.chartjs.org/docs/3.8.0/samples/advanced/programmatic-events.html ist very close. Thanks!

function triggerTooltip(chart) {
const tooltip = chart.tooltip; 
if (tooltip.getActiveElements().length > 0) 
  { tooltip.setActiveElements([], {x: 0, y: 0}); } 
  else { 
   const chartArea = chart.chartArea; 
   tooltip.setActiveElements([
      {
        datasetIndex: 0,
        index: 0,
      }, {
        datasetIndex: 1,
        index: 0,
      }], 
     { x: (chartArea.left + chartArea.right) / 2, 
       y: (chartArea.top + chartArea.bottom) / 2, }); 
    } 
chart.update(); } 

I did expect that the index controlls the bar, for the tooltip. But it makes no difference, whatever Index is set. Also when I change x,y it is still on the same place (close to 3rd bar). enter image description here


Solution

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