Chart.js getElementsAtEvent is returning empty array for line chart
Asked Answered
F

1

6

We are using Chart.js 2.1.4 in a project we are working on. When trying to get the point where a line chart was clicked on, the getElementsAtEvent function is returning an empty Array. I understand this is expected behavior if the user clicks arbitrarily on the chart, but it is also occurring even if the user clicks on a datapoint. Here is our onClick event handling:

options: {
    onClick: function(evt){
        var firstPoint = this.getElementAtEvent(evt);

        if (firstPoint) {
            console.log(firstPoint);
        } else {
            console.log('No point returned');
        }
    },

In the above code, firstPoint is an Array object with no items in it.

Firmament answered 8/6, 2018 at 14:3 Comment(1)
Try: var firstPoint = this.whateverYourChartVariableIs.chart.getElementAtEvent(event); Don't think this.getelementAtEvent is a function.Jute
C
0

getElementsAtXAxis will solve your problem.

  1. https://mcmap.net/q/1529658/-chart-js-get-the-nearest-point-when-clicked-on-canvas
Chalmers answered 3/1, 2021 at 21:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.