[Chartjs]-Get Dataset Values from Chart JS onHover in Version 3

1👍

You are using chart.js v3, in v3 there is no getElementAtEvent, it has been replaced with getElementsAtEventForMode. You can use this to get the active elements but you can also use the second argument the onHover function recieves which is an array with all the active elements:

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderColor: 'pink'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderColor: 'orange'
      }
    ]
  },
  options: {
    onHover: (evt, activeEls, chart) => {
      if (activeEls.length === 0 || chart.getElementsAtEventForMode(evt, 'nearest', {
          intersect: true
        }, true).length === 0) {
        return;
      }

      console.log('Function param: ', activeEls[0].index);
      console.log('lookup with the event: ', chart.getElementsAtEventForMode(evt, 'nearest', {
        intersect: true
      }, true)[0].index);

      activeEls.forEach(point => {
        console.log('val: ', chart.data.datasets[point.datasetIndex].data[point.index])
      })
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.js"></script>
</body>

Leave a comment