简体   繁体   中英

Run JS script when input range reaches certain value

I have an input range slider on my page that displays several values. I want to change CSS values of the elements on the same page when the value changes. I am well aware of the onChange function but I was wondering if there was a way to run the function changeAtt when it reaches a specific value, eg 2.

HTML:

<div id="change"></div>
<input class="slider "type="range" min="0" max="3" value="0" step="1" onchange="showValue(this.value)" />
<span id="range">0</span>

CSS:

#change {
    color:black;
}

JS:

function showValue(newValue) {
    document.getElementById("range").innerHTML=newValue;
}
function changeAtt() {
    document.getElementById("change").style.color = "white";
}

You can just call the changeAtt() function from showValue() if the value reaches a certain predefined amount.

function showValue(newValue) {
    document.getElementById("range").innerHTML=newValue;
    if(newValue === 2) {
        changeAtt();
    }
}
function changeAtt() {
    document.getElementById("change").style.color = "white";
}

I think you will just have to check the value in onChange event and give the further call

function showValue(newValue) {
     if(newValue === '2') changeAtt()
     document.getElementById("range").innerHTML=newValue;
}
function changeAtt() {
    document.getElementById("change").style.color = "white";
}

How about using oninput Event like this and then applying to your solution:

function myFunction(val) {
  document.getElementById("demo").innerHTML = val;
  if (val <= 300) {
    document.getElementById("change").style.color = "red";
  } else if (val > 300) {
    document.getElementById("change").style.color = "blue";
  }
}

And then:

<div id="change"><p id="demo">50</p>
</div>
<input id="pricing" type="range" min="50" max="301" step="1" oninput="myFunction(this.value)">

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