[Chartjs]-Chart js show/hide legend during runtime via buttonClick

1đź‘Ť

âś…

It looks like you were just trying to update the wrong legend config in the chart.js instance object. Here is the correct way.

document.getElementById('hideLEgend').addEventListener('click', function() {
  // toggle visibility of legend
  myLine.options.legend.display = !myLine.options.legend.display;
  myLine.update();
});

The thing that you were trying to update (e.g. chart.legend.options) is just the default legend configuration object. This gets merged with whatever options you define in your chart’s options.legend config.

Here is a codepen example showing the legend show/hide behavior from a button click.

You could also opt to not use the built in legend and generate your legend as pure HTML/CSS anywhere on your page, and then use jQuery (or standard javascript) to show and hide. I won’t provide an example for the showing/hiding (see jQuery’s show/hide functions) but I will demonstrate how to generate a custom legend. First you need to use the options.legendCallback option to create a function that generates the custom legend.

options: {
  legend: {
    display: false,
    position: 'bottom'
  },
  legendCallback: function(chart) {
    var text = [];
    text.push('<ul class="' + chart.id + '-legend">');
    for (var i = 0; i < chart.data.datasets.length; i++) {
    text.push('<li><div class="legendValue"><span style="background-color:' + chart.data.datasets[i].backgroundColor + '">&nbsp;&nbsp;&nbsp;&nbsp;</span>');

    if (chart.data.datasets[i].label) {
      text.push('<span class="label">' + chart.data.datasets[i].label + '</span>');
    }

    text.push('</div></li><div class="clear"></div>');
    }

    text.push('</ul>');

    return text.join('');
  }
}

Then use the .generateLegend() prototype method to generate the template (which executes the legendCallback function defined above) and insert it into the DOM.

$('#legend').prepend(mybarChart.generateLegend());

Here is a codepen example that demonstrates the custom legend approach. You can modify the legendCallback function to use whatever HTML you want for the legend structure and then use standard CSS to style it. And finally, use javascript to show/hide it on the button click.

0đź‘Ť

Did you try putting it in a div and hide/show it with CSS? it will be present but hidden and update() will make changes to the existing data so when u want it, just remove class “hidden”.

Leave a comment