Get point index from chart.getPointsAtEvent(e)

Hi, I am looking to make my chart 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?

Author: Fantashit

2 thoughts on “Get point index from chart.getPointsAtEvent(e)

  1. @tyrex1975 It’s not working for me, an error Uncaught TypeError: Cannot read property 'currentDevicePixelRatio' of undefined not leaving me alone.

    var activePoints = lineChart.getElementsAtEvent(evt);
    var mouse_position = Chart.helpers.getRelativePosition(evt); 
    
    activePoints = $.grep(activePoints, function(activePoint, index) {
    	var leftX = activePoint.x - 5,
    		rightX = activePoint.x + 5,
    		topY = activePoint.y + 5,
    		bottomY = activePoint.y - 5;
    
    	return mouse_position.x >= leftX && mouse_position.x <=rightX && 
                            mouse_position.y >= bottomY && mouse_position.y <= topY;
    });
    
    console.log(activePoints[0]);
    console.log('activePoints[0]----');
    
  2. I made a workaround to get data from the clicked point;
    As we know, the hover event fires before the event click, so I suggest the following solution

    // declare a global variable
    var selectedPoint;
    // add the code below to your chartjs options
    options: {
        .....,
        tooltips: {
            mode: 'single',
            callbacks: {
                afterBody: (data) => {
                    if(data && data[0])
                    selectedPoint = data[0];
                    return [''];
                }
            }
    }
    // here you can use the global variable
    canvas.onclick = function(e) {
       if(selectedPoint){
             // retrieve the data directly from selected point
             console.log("xLabel : "+selectedPoint.xLabel +" ,yLabel : "+selectedPoint.yLabel);
             // you can also retrieve the data && datasets
            console.log("datasets",myChart.config.data.datasets[selectedPoint.datasetIndex]);
    console.log("data",myChart.config.data.datasets[selectedPoint.datasetIndex].data[selectedPoint.index]);
       }
    };
    

Comments are closed.