Jüri Kiin
Jüri Kiin

Reputation: 810

How can I update the position of a range input slider via vanilla js?

I'm trying to programmatically update the position of my input slider (type="range").

I'm setting the value, however, that won't update the position of the slider.

I've also tried using:

element.dispatchEvent(new Event('input'))

to force an input change. This event does fire, however, the slider won't visually update.

   function changeSliderPosition(position) {
       let e = document.getElementById('mySlider');
       e.value = position;
       //Also set the position of the slider to position
   }

I've seen some solutions that work in JQuery, but I don't want to include an entire library or even use it at all for such a seemingly small issue.

I'd appreciate any help with this problem!

Upvotes: 2

Views: 6139

Answers (1)

Scott Marcus
Scott Marcus

Reputation: 65808

Assuming that your slider (input type="range") has its min and max attributes set, all you need to do is set the value:

let input = document.getElementById("in");
let btn = document.querySelector("button");
let slider = document.querySelector("input[type='range']");

btn.addEventListener("click", function(){
  slider.value = input.value;
});
Enter the value you want: <input id="in"><button>Go!</button><br>
<input type="range" min="1" max="100">

Upvotes: 5

Related Questions