35👍
✅
You could accomplish this using the following on-click event handler for your chart …
canvas.onclick = function(evt) {
var activePoint = myChart.getElementAtEvent(evt)[0];
var data = activePoint._chart.data;
var datasetIndex = activePoint._datasetIndex;
var label = data.datasets[datasetIndex].label;
var value = data.datasets[datasetIndex].data[activePoint._index];
};
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩
var chartData = {
type: 'horizontalBar',
data: {
labels: ['A0224', 'A3681', 'A3984', 'A4101', 'A4150', 'B0682', 'Others'],
datasets: [{
label: "P1",
backgroundColor: '#cc3399',
data: [6, 7, 6, 8, 6, 10, 3]
}, {
label: "P2",
backgroundColor: '#0099ff',
data: [8, 9, 5, 8, 6, 10, 3]
}, {
label: "P3",
backgroundColor: '#0022ff',
data: [6, 7, 6, 8, 6, 10, 3]
}]
},
options: {
responsive: false,
legend: {
display: false
},
scales: {
yAxes: [{
stacked: true
}],
xAxes: [{
stacked: true
}]
},
}
}
var canvas = document.getElementById('createCurrYearHccGapChart');
var myChart = new Chart(canvas, chartData);
canvas.onclick = function(evt) {
var activePoint = myChart.getElementAtEvent(evt)[0];
var data = activePoint._chart.data;
var datasetIndex = activePoint._datasetIndex;
var label = data.datasets[datasetIndex].label;
var value = data.datasets[datasetIndex].data[activePoint._index];
console.log(label, value);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="createCurrYearHccGapChart" height="170"></canvas>
2👍
In the new version of Chart.js, the below code would work.
const ctx = $('#monitor');
monitorChart = new Chart(ctx, config);
ctx.on('click', function(evt) {
const points = monitorChart.getElementsAtEventForMode(evt, 'nearest', { intersect: true }, true);
if (points.length) {
const firstPoint = points[0];
const label = monitorChart.data.labels[firstPoint.index];
const slabel = monitorChart.data.datasets[firstPoint.datasetIndex].label;
const value = monitorChart.data.datasets[firstPoint.datasetIndex].data[firstPoint.index];
console.log(label, slabel, value);
}
});
You can check Here!
Source:stackexchange.com