Sometimes, we want to handle click events on charts in Chart.js and JavaScript.
In this article, we’ll look at how to handle click events on charts in Chart.js and JavaScript.
Handle Click Events on Charts in Chart.js and JavaScript
To handle click events on charts in Chart.js and JavaScript, we can add the onClick
method into our chart.
Then we can use the getElementsAtEventForNode
method to get the index of the data set entry that we clicked on.
For instance, we can write the following HTML:
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart" width="200" height="200"></canvas>
to add the script for Chart.js and canvas elements for the bar chart.
Then we can add the bar chart by writing:
const datasets = [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
const ctx = document.getElementById("myChart").getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
onClick(e) {
const activePoints = myChart.getElementsAtEventForMode(e, 'nearest', {
intersect: true
}, false)
const [{
index
}] = activePoints;
console.log(datasets[0].data[index]);
}
}
});
We have the datasets
array with the data, border color, and bar colors we want to display.
Also, we have the label to set the label of the legend.
Next, we have the options
property set to an object with the onClick
method to catch any clicks that were made on the chart.
In it, we call myChart.getElementsAtEventForNode
method with the e
event object, 'nearest'
and an object with intersect
set to true
to get the nearest object that’s been clicked on.
It returns an array with the index
of the dataset
data entry that we clicked on.
Then we can get the value of the bar that we clicked on with:
datasets[0].data[index]
Conclusion
To handle click events on charts in Chart.js and JavaScript, we can add the onClick
method into our chart.
Then we can use the getElementsAtEventForNode
method to get the index of the data set entry that we clicked on.