PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, April 22, 2022

[FIXED] How to drill down charts with ChartJS?

 April 22, 2022     chart.js, drilldown, javascript, jquery, pie-chart     No comments   

Issue

I was very surprised that I found almost no information about this topic.

I have a ChartJS pie chart that I want to drill down into after clicking a slice of the pie.

How would you do that?

Thank you


Solution

I've solved my problem using this awesome answer:

Click events on Pie Charts in Chart.js

The code:

    $(document).ready(function() {
      var canvas = document.getElementById("myChart");
      var ctx = canvas.getContext("2d");
      var myNewChart = new Chart(ctx, {
         type: 'pie',
         data: data
      });

      canvas.onclick = function(evt) {
      var activePoints = myNewChart.getElementsAtEvent(evt);
      if (activePoints[0]) {
         var chartData = activePoints[0]['_chart'].config.data;
         var idx = activePoints[0]['_index'];

         var label = chartData.labels[idx];
         var value = chartData.datasets[0].data[idx];
         var color = chartData.datasets[0].backgroundColor[idx]; //Or any other data you wish to take from the clicked slice

         alert(label + ' ' + value + ' ' + color); //Or any other function you want to execute. I sent the data to the server, and used the response i got from the server to create a new chart in a Bootstrap modal.
       }
     };
  });

That works perfectly. Just instead of alerting the information, i send it to the server using AJAX, and displaying a new chart in a bootstrap modal.



Answered By - AlonBA
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing