简体   繁体   中英

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!

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"> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM