Chartjs-How to add an event when clicking a bubble in bubble chart?

1👍

I solved this by adding onClick: function(e) in the options, as shown below:

  let labels = [];
  let values = [];
  let ctx = "bubble_l1_chart"

  result.data.traits.forEach((a) => {
    labels.push(a._id)
    values.push({y:a.y, x:a.x, r: 5, z:a.z, desc: a._id})
  })

  bubbleChart = new Chart(ctx,{
    type: 'bubble',
    data: {
      labels: labels,
      datasets: [{
        data: values
      }]
    },
    options: {
      onClick: function(e) {
          var element = this.getElementAtEvent(e);

          if (element.length > 0) {
              var datasetLabel = this.config.data.datasets[element[0]._datasetIndex].label;
              var data = this.config.data.datasets[element[0]._datasetIndex].data[element[0]._index];

              //add code here to do whatever you want
              console.log(data);
          }
      }          
    }
  });

Explanation: Create a function inside of the new Chart(), and then feed the object in using data values.

Notice how I added a ‘desc’ key in the data values, so that I can identify the id of the bubble that was clicked.

Leave a comment