The question might suggest that I need onchange
, which is not the case. Compare these two snippets:
var slider = document.getElementById("slider")
slider.onchange = function() {
var currentVal = slider.value
document.querySelector("b").innerText = "The current value is " currentVal.toString()
}
<input type="range" id="slider" min="1" max="10" step="1" , value="4">
<br>
<b>The current value is 4</b>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
var slider = document.getElementById("slider")
slider.onmousemove = function() {
var currentVal = slider.value
document.querySelector("b").innerText = "The current value is " currentVal.toString()
}
<input type="range" id="slider" min="1" max="10" step="1" , value="4">
<br>
<b>The current value is 4</b>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
The upper one uses onchange
and only updates once the mouse is released.
The lower one uses onmousemove
and updates every time the mouse gets moved over the slider. However, I don't think that is the most memory saving method. It also doesn't change when using the arrow keys unless the mouse is moved over the slider.
Is there a certified or at least better way of doing what the lower one achieves?
CodePudding user response:
Just use oninput
Event, it will call when user slides on modern browsers.
var slider = document.getElementById("slider")
slider. oninput = function() {
var currentVal = slider.value
document.querySelector("b").innerText = "The current value is " currentVal.toString()
}
<input type="range" id="slider" min="1" max="10" step="1" , value="4">
<br>
<b>The current value is 4</b>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>