Chart.js: getElementsAtEvent with multiple bar charts always returns the same datasetIndex

Created on 12 Jul 2016  ·  7Comments  ·  Source: chartjs/Chart.js

getElementsAtEvent always returns an element with _datasetIndex: 0

https://jsfiddle.net/j3xy8ozg/

Clicking on any of the chart elements (even those in the second dataset) will print out a ChartElement with _datasetIndex: 0

support

Most helpful comment

Oh I found out how to do it. Use getDatasetAtEvent() along with getElementsAtEvent()

getElements gives you all the bars at the x value, while getdataset gives you all the elements that have the same dataset as the one being clicked.

Using them together produces this result.. https://jsfiddle.net/w6oxwwte/

All 7 comments

Try this one, looks like the old link is wrong

https://jsfiddle.net/8ygvLaax/4/

This one returns both ChartElements at each label - is there a way to tell which dataset was actually clicked?

Yes please. Anyone have any idea?....I'm trying to single out which bar is clicked in a multi bar graph, but nothing within the object getElementsAtEvent() returns tells me which one is actually clicked over. Thanks!

Oh I found out how to do it. Use getDatasetAtEvent() along with getElementsAtEvent()

getElements gives you all the bars at the x value, while getdataset gives you all the elements that have the same dataset as the one being clicked.

Using them together produces this result.. https://jsfiddle.net/w6oxwwte/

The underlying cause of this behaviour is that getElementsAtEvent was designed for use with the label tooltip mode. getElementAtEvent will get the first found element and is used for the single mode tooltip.

Oh I found out how to do it. Use getDatasetAtEvent() along with getElementsAtEvent()
getElements gives you all the bars at the x value, while getdataset gives you all the elements that have the same dataset as the one being clicked.
Using them together produces this result.. https://jsfiddle.net/w6oxwwte/

Thanks a lot DankDivinity. You saved me from a big headache.
I used below code and it worked perfectly.
var dIndex = chart.getDatasetAtEvent(e)[0]._datasetIndex;

I was fiddling around a bit, extending an existing fiddle from an answer on SO and made the pie slices also clickable for hiding them. But what I really would want is a clickable legend for bar charts that doesn't hide whole datasets but just items like for pie/doughnut/polarArea...

https://jsfiddle.net/90fu5pv4/

Lol what was I doing 3 years ago

Was this page helpful?
0 / 5 - 0 ratings