0

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?

enter image description here

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>
1
  • 1
    As said below, your variable names are causing your issue. You might have seen this a bit more clearly had you not used two <script></script> tags. You don't need to put them back to back like you did. One would suffice. Commented Jun 12, 2019 at 12:43

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I just edited the lines demo.innerHTML = this.value; and demo2.innerHTML = this.value; which also worked for some reason

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.