How to set action on slice-click Doughnut in Chart.js

Question:

I’ve been trying to add chart.js to my Django Project, which worked pretty fine so far. I made a doughnut-chart with two slices. Now i want to have each of those slices to have seperate actions on click, like for example redirecting to new side.

These are my chart settings:

var config = {
       type: 'doughnut',
       data: {
         datasets: [{
           data: {{ data|safe }}, // Error because django and js are being mixed
           backgroundColor: [
           '#ff0000', '#008000'
           ],
           label: 'Population'
         }],
         labels: {{ labels|safe }}
       },
       options: {
         responsive: true
       }
     };

And this is the rendering and my function to make the actions on click:

       window.onload = function() {
       var ctx = document.getElementById('pie-chart').getContext('2d');
       var myPieChart = new Chart(ctx, config);

       $('#myChart').on('click', function(event) {
          var activePoints = myPieChart.getElementsAtEvent(event)

          if(activePoints[0]){
            console.log("Helo 1")
          }
          
          else {
            console.log("helo 2")
          }
       })

     };

I saw my solution on other pages, but it doesn’t work at all. Am I missing something? If yes could you please help?

Asked By: whoami0605

||

Answers:

getElementAtEvent has been replaced with chart.getElementsAtEventForMode in Chart.js v3 (see 3.x Migration Guide).

Please take a look at below runnable code and see how it works now:

const pieChart = new Chart("myChart", {
  type: 'pie',
  data: {
    labels: ["Red", "Blue", "Yellow"],
    datasets: [{      
      data: [8, 5, 6],
      backgroundColor: ["#FF6384", "#36A2EB", "#FFCE56"],
    }]
  },
  options: {
    onClick: evt => {
      var elements = pieChart.getElementsAtEventForMode(evt, 'index', { intersect: true }, false);
      var index = elements[0].index;
      console.log(pieChart.data.labels[index] + ': ' + pieChart.data.datasets[0].data[index]);
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
<canvas id="myChart"></canvas>

Answered By: uminder