Highlight doughnut segment on mouseenter generateLegend Chartjs 2

2.4k views Asked by At

As the title says, I'm trying to highlight a segment in the chart according to the legend (on mouseenter event). I am using the generateLegend to create my custom legend but I am not sure how to attach the mouseenter event to each item.

This is what I have so far link

window.onload = function() {

setTimeout(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();

  }, 300);

  }

Any tip or help with the code would be great, I have been spending hours but no success and the docs are not really clear about this.

2

There are 2 answers

1
ɢʀᴜɴᴛ On BEST ANSWER

You can use the following function to highlight the corresponding segment of a doughnut chart, when hovered over a custom legend item :

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();
}

But, first you need to attach two event-listeners (mouseenter and mouseleave) to each of your li (legend) elements/items and then call the above function, passing the chart-instance, legend-item-index and a boolean value (whether to add/remove highlight), as the first, second and third arguments respectively.

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ

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();
}
#pie-wrapper {
   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;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<div id="pie-wrapper">
   <canvas id="outer-circle" width="300" height="300"></canvas>
</div>
<div id="diagram-legend"></div>

0
Vikram Ravichandran On
    color: [
      {
        backgroundColor: ['#92d06f', '#73c8b8', '#3bb9ab'],
        borderColor: 'rgba(255, 255, 255, 0)',
        hoverBackgroundColor: ['#92d06f', '#73c8b8', '#3bb9ab'],
        hoverBorderColor: ['#92d06f', '#73c8b8', '#3bb9ab'],
        hoverBorderWidth: 10,
        hoverRadius: 0
      }
   ],

It Works fine on mouse enter highlights the active segment in angular 2 (ng2 charts) for doughnut chart