Show/hide legend without chart reflowing into the empty space
author(s):
Mike Zavarello
HTML
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="container" style="height: 300px"></div>
<button id="updateLegend">Show or Hide Legend</button>
<button id="showAll">Show all Lines</button>
<button id="hideAll">Hide all Lines</button>
JavaScript
$(function () {
var chartOptions = {
chart: {
borderWidth: 1,
plotBorderWidth: 1,
renderTo: 'container'
},
legend: {
align: 'right',
verticalAlign: 'top',
layout: 'vertical',
y: 100
},
plotOptions: {
line: {
animation: false
}
},
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
series: [{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
},{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4].reverse()
}]
};
var chart = '';
var showLegend = false;
function drawChart() {
if (showLegend) {
chartOptions.legend.y = 100;
} else {
chartOptions.legend.y = -1000;
}
chart = new Highcharts.Chart(chartOptions);
};
drawChart();
$('#updateLegend').click(function (e) {
if(showLegend) {
showLegend = false;
drawChart();
} else {
showLegend = true;
drawChart();
}
});
// show all lines
$('#showAll').on('click', function() {
var series = chart.series;
for(i=0;i<series.length;i++) {
if (!series[i].visible) series[i].show();
};
drawChart();
});
// hide all lines
$('#hideAll').on('click', function() {
var series = chart.series;
for(i=0;i<(series.length - 1);i++) {
if (series[i].visible) series[i].hide();
};
drawChart();
});
});