linthum linthum - 18 days ago 5
Javascript Question

Input range not moving in javascript

screenshot of slider

I'm trying to move the slider on START button click.

function timer(){
var slider = document.getElementById("slider")
slider.setAttribute("value",counter)
slider.addEventListener("change", function(){
document.getElementById("output").innerHTML = this.value;
counter = parseInt(this.value);
});}


I can increment the counter, using setInterval on every second to display the year.
But, I am not able to move the slider according to the year value

I don't intend to use jQuery. Is it possible to do only using pure JS?

Code for slider :

1900<input type="range" id="slider" min="1900" max="2015" value="1900">2015




Code for button:

<button onclick="mytimer = setInterval(timer,1000)">START</button>
<button onclick="clearInterval(mytimer)">STOP</button>

Answer

Declare the change function outside the timer - you dont need it in there. And then in your timer, actually SET the value!

var slider = document.getElementById("slider");
slider.addEventListener("change", function(){
    document.getElementById("output").innerHTML = this.value;
    counter = parseInt(this.value);
});

function timer(){
    slider.value = slider.value + 1; //increment;
}

And, stop using inline JavaScript - it clutters the HTML and makes the JS harder to understand at a glance:

var mytimer = null;
function startTimer() {
    mytimer = setInterval(timer,1000)
}

function stopTimer() {
    clearInterval(mytimer);
}

<button onclick="startTimer()">START</button>
<button onclick="stopTimer()">STOP</button>

Preferably you'd even remove the onclick and switch everything to addEventListener - but the above is a good start