Highcharts: Hide and show legend
highcharts, javascript, jquery
Solution
In case when you destroy legend, then you need to generate full legend. Simpler solution is use hide() / show() function for elements.
http://jsfiddle.net/sbochan/3Bh7b/1/
$('#updateLegend').click(function (e) {
var legend = chart.legend;
if(legend.display) {
legend.group.hide();
legend.box.hide();
legend.display = false;
} else {
legend.group.show();
legend.box.show();
legend.display = true;
}
});
Problem
I'd like to be able to toggle the visibility of the legend of a chart when the user clicks a button. I've tried hiding the legend using the undocumented `destroy()` method, however when I try to re-render the legend and it's items, the items appear in the top left of the chart instead of within the legend. The items also don't seem to have any of their event handlers attached (clicking on an item no longer toggles a series). Is there a better way to do this? I have to support both SVG and VML implementations, so am looking for a solution that would address both. JSFiddle Example ``` $('#updateLegend').on('click', function (e) { var enable = !chart.options.legend.enabled; chart.options.legend.enabled = enable; if (!enable) { chart.legend.destroy(); //"hide" legend } else { var allItems = chart.legend.allItems; //add legend items back to chart for (var i = 0; i < allItems.length; i++) { var item = allItems[i]; item.legendItem.add(); item.legendLine.add(); item.legendSymbol.add(); } //re-render the legend chart.legend.render(); } }); ```