Reputation: 3518
I have a sprite image used in background of a div, i want to change it's position after every 1 second.
i tried following code but it's not working:
var speed = 1000;
var height = 50;
for (var i=0; i<dummyArray.length; i++) {
$("#char").delay(speed).animate({'background-position': '0 ' + -(heigth*i) +'px'}, 0);
}
Any suggestion please?
Upvotes: 0
Views: 1719
Reputation: 3711
I don't believe you can animate background-position with jQuery (at least, not without a plugin such as http://www.protofunc.com/scripts/jquery/backgroundPosition/); you could use a setInterval method:
var height = 50;
var i = 0;
var speed = 1000;
setInterval(function(){
i++;
if(i > dummyArray.length){
i = 0;
}
$("#char").css({'background-position' : '0 ' + (i*height) + 'px' });
}, speed);
be advised that this will cause the background position to jump rather than animate smoothly...
Upvotes: 1
Reputation: 5774
Are you sure you want to do that from within a for loop? You will end up with multiple animation events bound to the element that will fire at pretty much the same time. You may want to use a setInterval
or setTimeout
instead:
var counter = 1;
var height = 50;
var newInt = setInterval(function(){
$("#char").animate({'background-position': -(height*counter) +'px'});
counter++;
}, 1000);
Then to clear that interval and stop the animation you would use:
clearInterval(newInt);
Upvotes: 1