Chartjs doughnut hover event - Javascript Chart.js

Javascript examples for Chart.js:Doughnut Chart

Description

Chartjs doughnut hover event

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.min.js"></script> 
      <style type="text/css">

.container {//from ww  w  .  ja v a 2s.  c  o m
   width: 80%;
   margin: 15px auto;
}


      </style> 
   </head> 
   <body> 
      <div class="container"> 
         <h2>Chart.js ? Pie Chart Demo (apples)</h2> 
         <div> 
            <canvas id="myChart"></canvas> 
         </div> 
      </div> 
      <script type="text/javascript">
            var currentIndex = -1;
            Chart.defaults.global.hover.onHover = function(x) {
                if(x[0]) {
                    var index = x[0]._index;
                    if (index !== currentIndex) {
                        currentIndex = index;
                        console.log(x[0]._model.label + ': ' + x[0]._chart.config.data.datasets[0].data[index]);
                    }
                }
            };
            var ctx = document.getElementById("myChart").getContext('2d');
            var myChart = new Chart(ctx, {
              type: 'pie',
              data: {
                labels: ["M", "T", "W", "T", "F", "S", "S"],
                datasets: [{
                  backgroundColor: [
                    "#2ecc71",
                    "#3498db",
                    "#95a5a6",
                    "#9b59b6",
                    "#f1c40f",
                    "#e74c3c",
                    "#34495e"
                  ],
                  data: [12, 19, 3, 17, 28, 24, 7]
                }]
              }
            });
        
      </script>  
   </body>
</html>

Related Tutorials