[Chartjs]-How can I get the active label element on click in ChartJS?

13👍

The pie/doughnut charts don’t use a scale so you can’t use getValueForPixel. Instead you can just listen to the second argument which contains an array with all the active elements which for the default interaction mode only contains 1 item:

var options = {
  type: 'pie',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
    }]
  },
  options: {
    onClick: (e, activeEls) => {
      let datasetIndex = activeEls[0].datasetIndex;
      let dataIndex = activeEls[0].index;
      let datasetLabel = e.chart.data.datasets[datasetIndex].label;
      let value = e.chart.data.datasets[datasetIndex].data[dataIndex];
      let label = e.chart.data.labels[dataIndex];
      console.log("In click", datasetLabel, label, value);
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.js"></script>
</body>

Leave a comment