[Chartjs]-Chart.js is it possible to fire javascript when clicking on point on the graph?

4👍

Yes you sure can! Just use the .getDatasetAtEvent(e) or .getElementsAtEvent(e) prototype methods (depending on your needs). Here is more detail on what they do.

Looks for the element under the event point, then returns all elements at the same data index. This is used internally for ‘label’ mode highlighting.

Calling getElementsAtEvent(event) on your Chart instance passing an argument of an event, or jQuery event, will return the point elements that are at that the same position of that event.

Here is an example for how to get the point that was clicked when there are more than 1 datasets. Assuming my canvas has an id of canvas and my chart instance is called myLine.

document.getElementById("canvas").onclick = function(evt){
  var activePoints = myLine.getElementAtEvent(event);

  // make sure click was on an actual point
  if (activePoints.length > 0) {
    var clickedDatasetIndex = activePoints[0]._datasetIndex;
    var clickedElementindex = activePoints[0]._index;
    var label = myLine.data.labels[clickedElementindex];
    var value = myLine.data.datasets[clickedDatasetIndex].data[clickedElementindex];     
    alert("Clicked: " + label + " - " + value);
  }
};

You can also experiment with this codepen example.

Leave a comment