I'm a beginner of js. I wanna update a text as long as the value of a slider changes. Since the slider might be changed without click, I decide to use .onchange to detect if the value of the slider is changed. However, it doesn't work. The text is only be updated if the change of the slider is made by clicking. I'm wondering if there is a good way to detect any change of the slider? Thanks!
btw I also have tried the .oninput but I got the same result:(.
So here is my current code
// definition of slider and p in HTML
<input type="range" min="0" max="100" id="slider1" value="0"><p id=p1>0</p><br />
...
// In js, so the slider can affect each other
slider1.onclick = function(){
slider3.value = v2>v1?(v2-v1):(v1-v2);
}
slider2.onclick = function(){
slider3.value = v2>v1?(v2-v1):(v1-v2);
}
slider3.onclick = function(){
slider1.value = (slider3.value+slider2.value)%100;
}
// I wanna change the corresponding innerHTML when the value of slider is changed.
// However, the onchange isn't been triggered when the slider.value is changed
slider1.onchange=function(){
p1.innerHTML=slider1.value;
}
slider2.onchange=function(){
p2.innerHTML=slider2.value;
}
In order to reference an HTML element from javascript, you must get a reference to it: setting the id from an HTML element allows us to identify it, but we must use the document to actually refer to it.
<input id="slider1" type="range" />
JS:
let slider1 = document.getElementById("slider1");
// Repeat for slider2 and slider3
let p1 = document.getElementById("p1");
// Repeat for p2 and p3
slider1.onclick = function(){
slider3.value = v2>v1?(v2-v1):(v1-v2);
}
// Rest of your code
</script>
See the Mozilla documentation on document.getElementById() for more info: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById