score:10

Accepted answer

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);
    };

score: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);
}

score:5

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);
    }
}

Related Query

More Query from same tag