Fun and games with repeating jQuery animations

If you've ever been tempted to start new animations in a jQuery callback closure, then don't. Bad things happen.

Exhibit A:

$('div.one').animate({'opacity':0}, 200, 'linear', function(){
  $('div.one').css('display', 'none');
  $('div.two').animate({'opacity':1});
});

So far so good. All's fine and dandy with this first animation on div.two, but if you later try to animate div.two a second time, weird stuff starts happening in which this first animation repeats itself several times after your new animation finished. Very annoying and hard to track down as (as far as I'm aware) there's nothing 'wrong' with doing things this way. I'm not sure if this bug always crops up, but it certainly did for me today. You might be lucky.

I'm now achieving the same thing with...

$('div.one').animate({'opacity':0}, 200, 'linear, function(){$(this).css('display', 'none')}');
$('div.two').delay(200).animate({'opacity':1});

...where I use jQuery's lovely new delay method to get things happening in the right order. Huzzah!

Posted by email 

0 comments

Leave a comment...