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!
This works:
DEMO
Don’t know if it is the best way though.
Note: You either have to run the code in the
body.onloadevent handler or put it at the bottom of the page.You can also try to play with the step size and the timeout time….
there was something else I wanted to say, but I forgot 😉Another note: You should always use expressive variable names. E.g. It was not clear that
xis used as a boolean indicator (at least not if you only have a quick lock at it).