0

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?

Alok Jain
  • 3,379
  • 3
  • 23
  • 42
  • Have you checked the spelling of your variables. Also, move the -ve sign into the bracket. See if it works. – Sagar Patil Jan 26 '12 at 13:53
  • Mind that your animation is only taking 0ms. which is nothing. – Tim Jan 26 '12 at 13:57
  • Don't know if this is your actual code, but you've misspelled the second instance of 'height'. – magicalex Jan 26 '12 at 14:01
  • @Tim i do not want animation to take time, so i have added 0ms, however it should be delayed for some time, that's why i have used delay function. – Alok Jain Jan 26 '12 at 14:08
  • 1
    If you don't want the animation to render (i.e. you want the background to jump to the new position) then use a setInterval together with $('#char').css({ 'background-position' *etc* });... – MassivePenguin Jan 26 '12 at 14:22

2 Answers2

1

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...

MassivePenguin
  • 3,701
  • 4
  • 24
  • 46
  • You can animate any css property with jquery, animate() function takes CSS property and it's value as first argument. – Alok Jain Jan 26 '12 at 14:07
  • See http://stackoverflow.com/questions/5171080/jquery-animate-background-position (second answer) for a possible solution... – MassivePenguin Jan 26 '12 at 14:09
1

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);
Steve O
  • 5,224
  • 1
  • 24
  • 26