How to listen to click events on a chart with Chart.js?

Sometimes, we want to listen to click events on a bar chart with Chart.js.

In this article, we’ll look at how to listen to click events on a chart with Chart.js.

How to listen to click events on a chart with Chart.js?

To listen to click events on a bar chart with Chart.js, we set the options.onClick property to an event handler function.

For instance, we write:

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>

<canvas id='myChart' style='width: 300px; height: 300px'></canvas>

to add the canvas for the chart.

Then we write:

const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ['Monday', 'Tuesday', 'Wednesday'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3],
      borderWidth: 1,
      borderColor: 'green'
    }]
  },
  options: {
    onClick(e) {
      console.log(e)
    }
  }
});

to set the options.onClick property to the click event listener.

Now when we click on an item in the chart, we should see the click event object logged.

Conclusion

To listen to click events on a bar chart with Chart.js, we set the options.onClick property to an event handler function.