2👍
✅
May be you could try the following approach:
options:{
...
onClick: pieChartClickEvent,
...
}
function pieChartClickEvent(event, array){
if(array[0]){
//do something
}
...
}
2👍
Presuming you’re using Chart.js version 2, this can be done as follows:
onClick: evt => {
var elements = pieChart.getElementsAtEvent(evt);
var index = elements[0]._index;
console.log(index)
}
Please consult section
.getElementsAtEvent(e)
from Chart.js v2 documentation.
Please take a look at below runnable code and see how it works:
const pieChart = new Chart("myChart", {
type: 'pie',
data: {
labels: ["Red", "Blue", "Yellow"],
datasets: [{
data: [8, 5, 6],
backgroundColor: ["#FF6384", "#36A2EB", "#FFCE56"],
}]
},
options: {
events: ['click', 'mousemove', 'touchstart', 'touchmove'],
onClick: evt => {
var elements = pieChart.getElementsAtEvent(evt);
var index = elements[0]._index;
console.log(index);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="myChart"></canvas>
Source:stackexchange.com