Emily lukuta
Emily lukuta

Reputation: 1

I have a range slider in which I want to control the value change. If slider value is greater than 0.. say good day

<div class="container"><div id="number">0</div>
        <input type="range" min="0" max="10" value="0" id="slider"></div>
<script>
        var slider=document.
            getElementById("slider");
        var number=document.
            getElementById("number");
        slider.oninput=function(){
            number.innerHTML=slider.
                value;}
</script>
<p id="demo">good evening</p>

For some reason it's not working when I have number or slider or slider.value in the if statement.

<script>

    if (number> '0' ){document.getElementById("demo").innerHTML = "Good day!";}
</script>

Upvotes: 0

Views: 1021

Answers (1)

NTR
NTR

Reputation: 1355

If what you want to do is change "Good evening" to "Good day!" when you move the slider to the right, below code should give you what you want.

var slider = document.getElementById("slider");
var number = document.getElementById("number");

slider.oninput = function() {
  number.innerHTML = slider.value;
  
  if (slider.value > 0) {
    document.getElementById("demo").innerHTML = "Good day!";
  } else {
    //Change the text back if slider is not greater than 0.
    document.getElementById("demo").innerHTML = "Good evening!";
  }
}
<div class="container">
  <div id="number">0</div>
  <input type="range" min="0" max="10" value="0" id="slider"></div>

<p id="demo">Good evening!</p>

Explanation: In your if condition you say number > '0'. number is an element and using it like that won't give you the value inside. Instead, I used the value directly from the slider with slider.value. Also, instead of comparing it with a string '0' I compare it with the correct type, an integer 0. Also, assuming you want "Good evening!" to come back when you go back to 0, I added the else part to handle when the number is not greater than 0.

There are other improvements that can be done but this code works fine. Let me know if this doesn't answer your question.

Upvotes: 1

Related Questions