Mouse Click Events in ChartJS 2.X

Hello,

I have been attempting to write mouse click events for a pie chart in ChartJS 2.X but the “getSegmentsAtEvent(evt)” function doesn’t seem to be available in the newer version.

Instead, I have getDataelementAtEvenyt(evt), getElementAtEvent(evt), and getElementsAtEvent(evt).

The problem is I am not sure how to use the object returned; it doesn’t have any of the previous types of functions/data that the existing object returned used to have.

How do I use the new objects/classes returned?

Thank you for your time.

Author: Fantashit

3 thoughts on “Mouse Click Events in ChartJS 2.X

  1. I too am looking to do the same as @kissgs

    Also, the ChartElement returned by getElementAtEvent seems to have all it’s properties prefixed with an underscore which feels like they’re for internal use only. It would be great if ChartElement exposed a formal (documented) API for extracting the underlying data.

  2. This works for me: FIDDLE INCLUDED

    document.getElementById("myChart").onclick = function(evt){
                var activePoints = myChart.getElementsAtEvent(evt);
                var firstPoint = activePoints[0];
                var label = myChart.data.labels[firstPoint._index];
                var value = myChart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
                alert(label + ": " + value);
            };
    
  3. How do i get the clicked point instead of first?
    For example i have a mixed chart, with bar and line charts, so i have like 4 datasets, i want to add a click listener that return the selected point.

    Edit:
    Nevermind, i found myself a solution, follow for anyone with same doubt:

    document.getElementById("myChart").onclick = function (evt) {
            var activePoints = myChart.getElementsAtEventForMode(evt, 'point', myChart.options);
            var firstPoint = activePoints[0];
            var label = myChart.data.labels[firstPoint._index];
            var value = myChart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
            alert(label + ": " + value);
        };
    

Comments are closed.