Highlight doughnut segment on mouse enter generated Legend Chartjs - Javascript Chart.js

Javascript examples for Chart.js:Legend

Description

Highlight doughnut segment on mouse enter generated Legend Chartjs

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>Chartjs 2 - Doughnut</title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script> 
      <style id="compiled-css" type="text/css">

#pie-wrapper {/*from  w  w  w.  j ava  2s  .  com*/
   width: 300px;
   height: 300px;
}
#diagram-legend ul {
   list-style: none;
   padding: 0;
   margin: 0;
}
#diagram-legend ul li {
   margin-bottom: 10px;
}
#diagram-legend ul li span {
   width: 15px;
   height: 15px;
   display: inline-block;
   vertical-align: sub;
   margin-right: 10px;
}


      </style> 
      <script type="text/javascript">
    window.onload=function(){
var outerCircle = new Chart(document.getElementById("outer-circle"), {
   "type": "doughnut",
   "data": {
      "labels": ["Beer", "Wine", "Pisco", "Vodka", "Rum", "Tequila"],
      "datasets": [{
         "label": "Drinks",
         "data": [
            30,
            20,
            5,
            15,
            15,
            15
         ],
         "backgroundColor": [
            "#fdc694",
            "#ad937c",
            "#d8c2ae",
            "#bab8b6",
            "#e5aa74",
            "#fcf0e5"
         ]
      }]
   },
   "options": {
      "legend": {
         "display": false
      },
      "tooltips": {
         "mode": 'label',
         "callbacks": {
            "label": function(tooltipItem, data) {
               return " " + data['labels'][tooltipItem['index']] + " " + data['datasets'][0]['data'][tooltipItem['index']] + '%';
            }
         }
      }
   }
});
var diagramLegend = document.getElementById('diagram-legend');
diagramLegend.innerHTML = outerCircle.generateLegend();
/*** Highlight Doughnut Segment on Legend Hover ***/
var legendItems = document.querySelectorAll('#diagram-legend li');
legendItems.forEach(function(item, itemIndex) {
   item.addEventListener('mouseenter', function() {
      highlightSegment(outerCircle, itemIndex, true);
   });
   item.addEventListener('mouseleave', function() {
      highlightSegment(outerCircle, itemIndex, false);
   });
});
function highlightSegment(chart, index, isHighlight) {
   var activeSegment = chart.getDatasetMeta(0).data[index];
   if (isHighlight) chart.updateHoverStyle([activeSegment], null, true);
   else chart.updateHoverStyle([activeSegment], null, false);
   chart.draw();
}
    }

      </script> 
   </head> 
   <body> 
      <div id="pie-wrapper"> 
         <canvas id="outer-circle" width="300" height="300"></canvas> 
      </div> 
      <div id="diagram-legend"></div>  
   </body>
</html>

Related Tutorials