onclickchart.jsdatapoint

Chart.js 2.x - How to get handle of only clicked datapoint?


I have a multiline chart drawn using chart.js. I want to get borderColor of the clicked point(datapoint) only, when the user clicks on a particular point.

For understanding, I have two lines in my multi-line chart called Prime and Fibonacci and My Second dataset drawn using dataset [12, 13, 15, 17, 111, 113, 117, 9, 3, 0] and [2, 3, 5, 7, 11, 13, 17, 13, 21, 34] respectively, both lines have a different borderColor green and red respectively.

Now, I want to catch only clicked point's borderColor when the user clicks on the datapoints. For example, when the user clicks on datapoint 111 which is from line Prime and Fibonacci then I should get borderColor as green, similarly when the user clicks on datapoint 11 from My Second dataset line, then I should get border color as red.

I have tried using below but it gives me both colors doesn't matter on which lines data point the user clicked.

var activePoints = lineChart.getElementsAtEvent(evt);
// Below code always gives me green and red, doesn't matter which line's data point the user clicked
activePoints[0]._chart.config.data.datasets[0].borderColor // Always gives green 
activePoints[0]._chart.config.data.datasets[1].borderColor // Always gives red

How can I do that? For quick setup take help of jsbin.

Thanks in Advance!


Solution

  • After a long struggle and research, I came up with below solution.

    It will give me _datasetIndex which is helpful to understand the click event triggered from Prime and Fibonacci or My Second dataset line. If activePoints[0]._datasetIndex is 0 then it's from Prime and Fibonacci, similarly if activePoints[0]._datasetIndex is 1 then it's from My Second dataset.

    ctx.onclick = function(evt) {
        var activePoints = lineChart.getElementsAtEvent(evt);
    
        if (activePoints.length) {
          var mouse_position = Chart.helpers.getRelativePosition(evt, lineChart.chart);
    
          activePoints = $.grep(activePoints, function(activePoint, index) {
            var leftX = activePoint._model.x - 5,
                rightX = activePoint._model.x + 5,
                topY = activePoint._model.y + 5,
                bottomY = activePoint._model.y - 5;
    
            return mouse_position.x >= leftX && mouse_position.x <=rightX && mouse_position.y >= bottomY && mouse_position.y <= topY;
          });
          console.log(activePoints[0]._datasetIndex);
        }    
    };
    

    That said, here is working example jsbin. I believe this is going to help many people who is having same scenario/problem.