How to use generated html legends to enable or disable datasets in chart.js?

by raven_corwin , in category: Javascript , 2 months ago

How to use generated html legends to enable or disable datasets in chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , 2 months ago

@raven_corwin 

To enable or disable datasets in Chart.js using generated HTML legends, you can follow these steps:

  1. Create an HTML element to serve as the container for your legends. For example, you can use a
  2. In your JavaScript code, create a Chart.js chart instance and store it in a variable. For example:
1
2
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, { /* Chart configuration */ });


  1. Add the legendCallback option to the chart configuration to generate the legend HTML. This option should be a function that returns the HTML string for the legend. For example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
var myChart = new Chart(ctx, {
  /* Chart configuration */
  options: {
    legendCallback: function(chart) {
      var legend = '';
      var datasets = chart.data.datasets;
      for (var i = 0; i < datasets.length; i++) {
        legend += '<div class="legend-item">';
        legend +=   '<span class="legend-color" style="background-color:' + datasets[i].backgroundColor + '"></span>';
        legend +=   '<span class="legend-label">' + datasets[i].label + '</span>';
        legend += '</div>';
      }
      return legend;
    }
  }
});


  1. After creating the chart and defining the legendCallback option, call the generateLegend() method on the chart instance. This method returns the generated HTML legend.
1
var legend = myChart.generateLegend();


  1. Append the generated legend HTML to the container element created in step 1. For example:
1
document.getElementById('chart-legend').innerHTML = legend;


  1. Now you can add event listeners to the legend items or checkboxes within the legend container to control the visibility of the datasets. You can achieve this by adding a click event listener to the legend items and toggling the hidden property of the corresponding dataset.
1
2
3
4
5
6
7
document.querySelectorAll('#chart-legend .legend-item').forEach(function(legendItem, index) {
  legendItem.addEventListener('click', function() {
    var dataset = myChart.data.datasets[index];
    dataset.hidden = !dataset.hidden;
    myChart.update();
  });
});


By implementing the above steps, you can use generated HTML legends to enable or disable datasets in Chart.js.