Chartjs-How to add on click event to chart js

2👍

This can be done with an onClick even handler as follows:

onClick: (event, elements, chart) => {
  if (elements[0]) {            
     const i = elements[0].index;
     alert(chart.data.labels[i] + ': ' + chart.data.datasets[0].data[i]);
  }
}

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

new Chart('myChart', {
  type: 'line',
  data: {
  labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [{
      label: '# of Votes',
      data: [65, 59, 80, 81, 56, 55, 40],
      borderColor: '#a00'
    }]
  },
  options: {
    onClick: (event, elements, chart) => {
      if (elements[0]) {            
         const i = elements[0].index;
         alert(chart.data.labels[i] + ': ' + chart.data.datasets[0].data[i]);
      }
    }
  }
});
<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>

Leave a comment