Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there a certified or at least better way of doing what the lower one achieves?

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading