Chart.js custom legend with doughnut chart - Javascript Chart.js

Javascript examples for Chart.js:Legend

Description

Chart.js custom legend with doughnut chart

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>Chart.js Pie custom legend</title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.js"></script> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0-rc.1/Chart.js"></script> 
      <style id="compiled-css" type="text/css">

.container {//  www.ja v  a2  s  .  c o m
   width: 80%;
   margin: 15px auto;
}
[class$="-legend"] {
   list-style: none;
   cursor: pointer;
   padding-left: 0;
}
[class$="-legend"] li {
   display: inline-block;
   padding: 0 5px;
}
[class$="-legend"] li.hidden {
   text-decoration: line-through;
}
[class$="-legend"] li span {
   border-radius: 5px;
   display: inline-block;
   height: 10px;
   margin-right: 10px;
   width: 10px;
}


      </style> 
      <script type="text/javascript">
    window.onload=function(){
var ctx = document.getElementById("myChart").getContext('2d');
var chart = new Chart(ctx, {
  type: 'pie',
  data: {
    labels: ["Green", "Blue", "Gray", "Purple", "Yellow", "Red", "Black"],
    datasets: [{
      backgroundColor: [
        "#2ecc71",
        "#3498db",
        "#95a5a6",
        "#9b59b6",
        "#f1c40f",
        "#e74c3c",
        "#34495e"
      ],
      data: [12, 19, 3, 17, 28, 24, 7]
    }]
  },
  options: {
    legend: {
      display: false
    },
  }
});
var myLegendContainer = document.getElementById("legend");
myLegendContainer.innerHTML = chart.generateLegend();
var legendItems = myLegendContainer.getElementsByTagName('li');
for (var i = 0; i < legendItems.length; i += 1) {
  legendItems[i].addEventListener("click", legendClickCallback, false);
}
function legendClickCallback(event) {
  event = event || window.event;
  var target = event.target || event.srcElement;
  while (target.nodeName !== 'LI') {
    target = target.parentElement;
  }
  var parent = target.parentElement;
  var chartId = parseInt(parent.classList[0].split("-")[0], 10);
  var chart = Chart.instances[chartId];
  var index = Array.prototype.slice.call(parent.children).indexOf(target);
  var meta = chart.getDatasetMeta(0);
  console.log(index);
   var item = meta.data[index];
  if (item.hidden === null || item.hidden === false) {
    item.hidden = true;
    target.classList.add('hidden');
  } else {
    target.classList.remove('hidden');
    item.hidden = null;
  }
  chart.update();
}
    }

      </script> 
   </head> 
   <body> 
      <div class="container"> 
         <h2>Chart.js ? Pie Chart Demo</h2> 
         <div> 
            <div id="legend"></div> 
            <canvas id="myChart"></canvas> 
         </div> 
      </div>  
   </body>
</html>

Related Tutorials