I am trying to update my Highcharts plotBands dynamically with sliders on the page. I want both to
and from
to be attached to slider values and dynamically updated on the canvas as the user drags the sliders. Is that possible?
HTML:
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="container"></div>
<!-- <input id="range" type="range" /> -->
<div id="slider">
<input class="bar" type="range" id="range-input" min="1" max="25" value="1"/>
<span class="highlight"></span>
<output id="range-value">1</output>
</div>
JS:
var rangeInput = document.getElementById("range-input")
var rangeValue = document.getElementById("range-value")
rangeInput.oninput = rangeOutput
function rangeOutput() {
rangeValue.innerText = rangeInput.value
}
let bla = rangeInput.value;
Highcharts.chart('container', {
chart: {
marginTop: 5
},
title: {
text: 'Flats sold per month'
},
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
yAxis: {
plotBands: [{
from: bla,
to: 5,
color: 'yellow'
}],
title: {
text: 'Flats'
}
},
series: [{
data: [1, 3, 5, 2, 3, 9, 6, 7, 3, 5, 4, 3]
}]
});
Where I get stuck is updating the chart in real time. I can see there are methods to do that if I want to update my data, but I’m not sure how to do that for plotBands.
2
Answers
We can use chart.update.
First, we set your chart as
chart
.And, now we use
chart.update
inrangeOutput
function.Here is a CodePen of the final code.
To update the plotBands dynamically when the slider values change, you need to modify your code to update the Highcharts chart’s yAxis options whenever the input range value changes. Here’s an example of how you can achieve this:
HTML:
JavaScript:
In this code, we store the reference to the Highcharts chart in the
chart
variable. On changing the slider value, therangeOutput
function is called, which updates the range value displayed and updates theplotBands
on the chart’s yAxis by using thechart.yAxis[0].update()
method.