Click events on Pie Charts in Chart.js - Javascript Chart.js

Javascript examples for Chart.js:Pie Chart

Description

Click events on Pie Charts in Chart.js

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.bundle.min.js"></script> 
      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){/*from w ww.ja  v a  2s .  c  om*/
var data = {
  datasets: [{
    data: [300, 50, 100],
    backgroundColor: [
      "#F7464A",
      "#46BFBD",
      "#FDB45C"
    ]
  }],
  labels: [
    "Red",
    "Green",
    "Yellow"
  ]
};
$(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 url = "http://example.com/?label=" + label + "&value=" + value;
        console.log(url);
        console.log(url);
      }
    };
  }
);
    }

      </script> 
   </head> 
   <body> 
      <div style="width: 300px; height: 300px"> 
         <canvas id="myChart"></canvas> 
      </div>  
   </body>
</html>

Related Tutorials