Chiyaan Suraj Chiyaan Suraj - 3 months ago 47
jQuery Question

How to catch an onClick event on bubble chart?

I am trying to catch an onlick event on a bubble in bubble chart. I want to log the label of clicked bubble into the console. I have written a function to do the job which actually looks like this

$("#myChart").click(function(evt) {
var activePoints = myBubbleChart.getElementAtEvent(evt);
console.log(activePoints.label);
});


Every time I click on a bubble this function logs "undefined" into console. I have even tried
getBarsAtEvent
and
getSegmentsAtEvent
none of them worked. What's wrong in my code? And can anybody please tell me how can I get the label value of bubble which I clicked?

Answer

Chart.js options have a built-in onClick property (see documentation).

It works like this :

options: {
     onClick: function(e) {
        var element = this.getElementAtEvent(e);

        // If you click on at least 1 element ...
        if (element.length > 0) {
            // Logs it
            console.log(element[0]);

            // Here we get the data linked to the clicked bubble ...
            var datasetLabel = this.config.data.datasets[element[0]._datasetIndex].label;
            // data gives you `x`, `y` and `r` values
            var data = this.config.data.datasets[element[0]._datasetIndex].data[element[0]._index];
        }
    }
}

Check this jsFiddle for a full example.