[Chartjs]-How to catch an onClick event on bubble chart?

4👍

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.

0👍

Getting the name of the clicked item, the current dataset, or the item in the current dataset is straightforward:

onClick: (e, i) => {
            const bubbleSelected = i[0];
            console.log(this.widget.data.bubblesData[bubbleSelected.datasetIndex].tooltipData[bubbleSelected.index]);
        }

Parameter i contains an array of clicked elements which contains the following:
enter image description here

With these image data, knowing which dataset you have selected and which element of the dataset you have clicked, you can, from an array of data, obtain the data, names or whatever you want from the current dataset of the current position.

In my case I had in bubblesData a list of datasets (datasetIndex) and in each dataset an object called tooltipData with a list of data for each element of the dataset (index).

enter image description here

If you want to see how to also modify the tooltip to show it like this visit this link: Chart JS Show HTML in Tooltip

Documentation:

Leave a comment