Chartjs-How to get clicked bar chart tooltip data?

4👍

You can use the following onClick function to get tooltip­‘s data :

onClick: function(event, element) {
   var activeElement = element[0];
   var data = activeElement._chart.data;
   var barIndex = activeElement._index;
   var datasetIndex = activeElement._datasetIndex;

   var datasetLabel = data.datasets[datasetIndex].label;
   var xLabel = data.labels[barIndex];
   var yLabel = data.datasets[datasetIndex].data[barIndex];

   console.log(datasetLabel, xLabel, yLabel);
}

also, you would need to set the hover mode of chart to nearest to get it working properly :

hover: {
   mode: 'nearest'
}

see a working example.

Leave a comment