Chiyaan Suraj Chiyaan Suraj - 11 months ago 131
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);

Every time I click on a bubble this function logs "undefined" into console. I have even tried
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 Source

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

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

Check this jsFiddle for a full example.