How to register plot or label click event in chart.js?

by edmond_brakus , in category: Javascript , 5 months ago

How to register plot or label click event in chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by orpha , 5 months ago

@edmond_brakus 

To register a click event in Chart.js and retrieve the clicked data point information, you can follow these steps:

  1. Get a reference to the chart instance using getElementById or querySelector:
1
var chart = document.getElementById('myChart').getContext('2d');


  1. Attach a click event listener to the chart canvas:
1
2
3
chart.canvas.addEventListener('click', function(event) {
  // Handle click event
});


  1. Inside the event listener, you can retrieve the clicked data point information using the getElementAtEvent method. This method returns an array of all elements that are at the same position as the click event:
1
var clickedElements = chart.getElementAtEvent(event);


  1. You can access the data point and dataset information using the index property provided in each clicked element. For example, to retrieve the label and value of the clicked data point, you can use:
1
2
3
4
5
6
7
if (clickedElements.length > 0) {
  var clickedElementIndex = clickedElements[0].index;
  var clickedDatasetIndex = clickedElements[0].datasetIndex;

  var label = chart.data.labels[clickedElementIndex];
  var value = chart.data.datasets[clickedDatasetIndex].data[clickedElementIndex];
}


Note: Replace 'myChart' with the ID of your chart canvas element.


You can further process or display the retrieved data as per your requirements.