I have a highchart displaying fuel types. I would like to hide certain fuel types based on a users profile. The if statement is an example as its the JS I can't get to work. I want this to hide the legend for the series named CNG but nothing happens. Where am I going wrong?
if( user profile does not include fuel type CNG ) : ?>
<script type='text/javascript'>
$(function () {
$('#container').highcharts({
series: [{
name: ['CNG'],
showInLegend: false
}]
});
});
</script>
<?php endif;
If you want to hide the series from the legend when the chart is initialized, it is as you have written:
series: {
showInLegend: false,
...
}
If you want to hide a series from the legend after the chart has been initialized, you have to use either chart.update
or chart.series[index].update
where chart is the variable containing your highchart object. Like this:
chart.series[0].update({
showInLegend: false
}, true, false);
This will hide the first serie's legend.
var chart = Highcharts.chart('container', {
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
showEmpty: false
},
yAxis: {
showEmpty: false
},
series: [{
name: 'First series',
data: [15,41,13,31,104,124,29,55,63,71],
}, {
name: 'Second series',
data: [14,51,123,31,134,123,23,5,6,7]
}]
});
// Toggle names
let toggle = true;
$('#legend').click(function () {
if(toggle) {
chart.series[0].update({
showInLegend: false
}, true, false);
toggle = false;
}
else {
chart.series[0].update({
showInLegend: true
}, true, false);
toggle = true;
}
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="container" style="height: 150px"></div>
<button id="legend">Toggle legend</button>
Working example: http://jsfiddle.net/ewolden/vkdcs79x/
Using jQuery to get the highcharts object can be done like this:
$('#container').highcharts().series[0].update({
showInLegend: false
}, true, false);
To trigger a update after the chart has loaded this can be used:
$('#container').ready(function() {
$('#container').highcharts().series[0].update({
showInLegend: false
}, true, false);
})
Working example: http://jsfiddle.net/ewolden/vkdcs79x/9/
</div>