[Chartjs]-Get yLabel value onclick chart js

12👍

This demo gives the value in the bar chart when you click on it.
I’m not a chart.js expert so there may be better solutions.

https://codepen.io/newschapmj1/pen/PerOzM

/* from https://github.com/chartjs/Chart.js/issues/2292 */
document.getElementById("myChart").onclick = function (evt) {
        var activePoints = myChart.getElementsAtEventForMode(evt, 'point', myChart.options);
        var firstPoint = activePoints[0];
        var label = myChart.data.labels[firstPoint._index];
        var value = myChart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
        alert(label + ": " + value);
    };

6👍

Chart.js version = 3.2.1

From the official documentation:

onClick: (evt) => {
    const points = myChart.getElementsAtEventForMode(evt, 'nearest', { intersect: true }, true);

    if (points.length) {
        const firstPoint = points[0];
        var label = myChart.data.labels[firstPoint.index];
        var value = myChart.data.datasets[firstPoint.datasetIndex].data[firstPoint.index];
        alert(label +" : "+ value);
    }
}

0👍

I needed a way to get the chart from the callback because I’m using the same callback for multiple charts, so I can’t just say myChart

This works, passing to chart options – the second parameter is called "activeElements" and can be used to get the chart:

onClick: (event, activeElements) => {
    if(activeElements.length === 0){
      alert("Chart is clickable but you must click a data point to drill-down")
    }
    const chart = activeElements[0]._chart
    const activePoints = chart.getElementsAtEventForMode(event, 'point', chart.options);
    const firstPoint = activePoints[0];
    const label = chart.data.labels[firstPoint._index];
    const value = chart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
    alert(label + ": " + value);
}

Leave a comment