Chartjs-How to set Custom tooltip event with Chartjs version 2.X

2πŸ‘

βœ…

The correct (documented) way to do this, per the api, is to use the .getElementAtEvent() prototype method.

The other answer kind of works, but does not work if your chart has more than 1 dataset (e.g. line). Plus, it relies on undocumented objects/properties in the chart.js object that could change at any time with a new release.

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

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

Here is a codepen example demonstrating the above code.

0πŸ‘

There is always a way to solve any issue. It took about half an hour but I found it.

in your jsfiddle, just change below:

canvas.addEventListener('click', function(e){
                var x = myChart;
}, false);
break;

to

canvas.addEventListener('click', function(e){
                var x = myChart;
                if(x.active[0]){
                    var value= x.tooltip._data.datasets["0"].data[x.active["0"]._index];
                    var label = x.tooltip._data.labels[x.active["0"]._index];
                    console.log(value + " at "+ label);
                }

}, false);
break;

You will have access to the point via label and value. enjoy πŸ™‚

Leave a comment