Skip to content
Advertisement

What is the best way to get a slider value every time it changes?

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>

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>

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?

Advertisement

Answer

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>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement