How to use generated HTML legends to enable or disable datasets - Javascript Chart.js

Javascript examples for Chart.js:Legend

Description

How to use generated HTML legends to enable or disable datasets

Demo Code

ResultView the demo in separate window

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

.myChartDiv {//from   www  .j a va2s .  c om
   max-width: 600px;
   max-height: 400px;
}
.chart-legend li span {
   display: inline-block;
   width: 12px;
   height: 12px;
   margin-right: 5px;
   margin-left: 20px;
}
.chart-legend ul {
   list-style-type: none;
}
.chart-legend ul li {
   float:left;
   cursor: pointer;
}
.inactive {
   opacity: .5;
}


      </style> 
   </head> 
   <body> 
      <div class="myChartDiv"> 
         <canvas id="myChart" width="600" height="400"></canvas> 
      </div> 
      <div id="js-legend" class="chart-legend"></div> 
      <script type="text/javascript">
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: 'Votes of 1st Round',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: '#1F699C',
        }, {
            label: 'Votes of 2nd Round',
            data: [4, 5, 7, 15, 6, 4],
            backgroundColor: '#C6C6C6',
        }]
    },
    options: {
         legend: {
                display: false
        }
    }
});
document.getElementById('js-legend').innerHTML = myChart.generateLegend();
$('#js-legend').click(function(e) {
    var targetLi = $(e.target).closest('li');
    targetLi.toggleClass('inactive');
    if (targetLi.hasClass('inactive')) {
         myChart.getDatasetMeta(targetLi.index()).hidden=true;
    } else {
        myChart.getDatasetMeta(targetLi.index()).hidden=false;
    }
      myChart.update();
});

      </script>  
   </body>
</html>

Related Tutorials