I am looking to make my chart (made with Chart.js) a little more interactive and I would like to get a point's index (of its dataset) with the following code:
canvas.onclick = function(e) {
const points = chart.getPointsAtEvent(e);
// something like `point.getIndex()` would be great so that I know where this point is in the original dataset
};
Anybody have a good solution for this?
I am looking to make my chart (made with Chart.js) a little more interactive and I would like to get a point's index (of its dataset) with the following code:
canvas.onclick = function(e) {
const points = chart.getPointsAtEvent(e);
// something like `point.getIndex()` would be great so that I know where this point is in the original dataset
};
Anybody have a good solution for this?
Share Improve this question asked Jul 6, 2015 at 18:54 MacksMacks 1,7767 gold badges23 silver badges39 bronze badges 1- I am currently solving this by looking up the index of the label but it is a bit hacky... – Macks Commented Jul 6, 2015 at 19:32
1 Answer
Reset to default 2You should be able to do an indexOf (instead of a label lookup) because it refers to the exact same object in the points collection
canvas.onclick = function (evt) {
var points = chart.getPointsAtEvent(evt);
alert(chart.datasets[0].points.indexOf(points[0]));
};
Also, for a multi series line chart getPointsAtEvent(evt)
returns points from all datasets. So the same code would work irrespective of how many datasets you have or which of the datasets you click on.
Fiddle - http://jsfiddle/yxz2sjam/