Reputation: 662
I want to create two range sliders in html and display their current value with a JS script below each slider. But in my code both sliders will output their value to the same "value output" (the one for the slider with id="myRange2"
). Why does this happen and how can I fix this?
I tried to make the slider
and output
variables unique for each slider script, but that does not solve my problem.
This issue is similar, but I am not so familiar with JS and I think my solution might be more simple.
This is my .html
code with the JS scripts at the end:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="slidecontainer">
<input type="range" min="1" max="100" value="50" class="slider" id="myRange">
<p>Value: <span id="demo"></span></p>
</div>
<div class="slidecontainer">
<input type="range" min="1" max="100" value="50" class="slider" id="myRange2">
<p>Value: <span id="demo2"></span></p>
</div>
<script>
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = slider.value;
slider.oninput = function() {
output.innerHTML = this.value;
}
</script>
<script>
var slider = document.getElementById("myRange2");
var output = document.getElementById("demo2");
output.innerHTML = slider.value;
slider.oninput = function() {
output.innerHTML = this.value;
}
</script>
</body>
</html>
Upvotes: 0
Views: 2679
Reputation: 5992
You have to use different names for variables
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="slidecontainer">
<input type="range" min="1" max="100" value="50" class="slider" id="myRange">
<p>Value: <span id="demo"></span></p>
</div>
<div class="slidecontainer">
<input type="range" min="1" max="100" value="50" class="slider" id="myRange2">
<p>Value: <span id="demo2"></span></p>
</div>
<script>
var slider1 = document.getElementById("myRange");
var demo = document.getElementById("demo");
demo.innerHTML = slider1.value;
slider1.oninput = function() {
demo.innerHTML = this.value;
}
</script>
<script>
var slider2 = document.getElementById("myRange2");
var output = document.getElementById("demo2");
output.innerHTML = slider2.value;
slider2.oninput = function() {
output.innerHTML = this.value;
}
</script>
</body>
</html>
Upvotes: 2