score:0

i believe you are looking for .getelementatevent and .getelementsatevent (https://www.chartjs.org/docs/latest/developers/api.html#getelementsatevente)

what you can do - is set up a clickhandler function that will grab the event from onclick and use it to return the chart element under it.

here is an example from the official docs:

function clickhandler(evt) {
    var firstpoint = mychart.getelementatevent(evt)[0];

    if (firstpoint) {
        var label = mychart.data.labels[firstpoint._index];
        var value = mychart.data.datasets[firstpoint._datasetindex].data[firstpoint._index];
    }
}

after, just add it to your chart canvas (again, from the official docs):

canvas.onclick = clickhandler;

score:4

i think you will find getelementsatxaxis very helpful.

basically, getelementsatxaxis has a very similar behaviour to getelementsatevent although when the click event doesn't intersect a point of the chart, it will return the nearest chartelement.

the only downside is that it will return all the chartelement on the nearest x-axis index.

so, if you use multiple datasets, this might not be the best choice for you.

code example:

canvas.onclick = function(e) {
    const elts = chart.getelementsatxaxis(simulatedevent);
    if (elts && elts.length) {
        // do something with elts[0]
    }
};

if anyone is looking for the related piece of code, it's in core.controller.js:

getelementatevent: function(e) {
    return interaction.modes.nearest(this, e, {intersect: true});
},

getelementsatevent: function(e) {
    return interaction.modes.index(this, e, {intersect: true});
},

getelementsatxaxis: function(e) {
    return interaction.modes.index(this, e, {intersect: false});
},

Related Query

More Query from same tag