the site is here I'm trying to create an animated button by moving the position of the background using Javascript when the user clicks the button. However, instead of slowly scrolling, the button jumps to the end of the loop. Here's the code:
var x=1, y=0, z=1;
function animate () {
document.getElementById("switch").style.backgroundPosition = y + 'px 0px';
}
function toggle() {
// check if button is on
if (x==1) {
//As long as image is not yet in place, move the background
while (y>-37) {
//Delay each move by 500 and increase the delay
setTimeout("animate()",500*z);
--y;++z;
}
--x;
//reset increasing timer
z=1;
}
// check if button is off
else if (x==0) {
//As long as image is not yet in place, move the background
while (y<0) {
//Delay each move by 500 and increase the delay
setTimeout("animate()",500*z);
++y;++z;
}
++x;
//reset increasing timer
z=1;
}
}
Please let me know how to fix. Thanks!
animate()is called the first time (bysetTimeout), thewhileloop already finished andywill have "end value" (e.g.-37). If you provide a simplified jsfiddle.net example, I would be more inclined to help you ;) But the basic idea would be to not start the timeouts all at once but each call creates a new timeout... something like that.