views:

690

answers:

3

When I use the fade/slide/animate functions in jQuery the callback gets called multiple times for each element the effect is applied to. This is by design of course. I just want to know when the last callback is called.

Here is what I came up with- it fades out all the divs and displays an alert() when the last callback is fired.

$("div").fadeOut(1000, function ()
{
     if ($("div").index($(this)) == $("div").length-1)
          alert("this is the final callback");
});

Is there a simpler way to check which callback is the last one or is this the only way to do it?

A: 
$("div:not(:last)").fadeOut(1000);
$("div:last").faedOut(1000, funtion() {
    alert("Hey!");
});
Gromer
nice, i haven't used not() before. good to know!
+2  A: 

That would produce the alert when the fadeOut on the last element was called. That would not necessarily be the last fadeOut.

var numDivs = $('div').length;
$('div').fadeOut(1000, function() {
  if( numDivs-- > 0 ) return;
  alert('this is the final fadeout to complete');
});
samjudson
Ahhh, I see what you're saying. Good call!
Gromer
yep, good thinking. I like the other solutions too but this one 100% correct.
Where is count defined?
Josh Stodola
Apologies - should be 'numDivs' inside the function.
samjudson
Shouldn't it actually be if( numDivs-- > 1 ) return;
Nicholas H
A: 

What you are doing seems fine, a more jQuery'ish version might be:

$("div").fadeOut(1000, function ()
{
     if ($(this).is(':last')) {
          alert("this is the final callback");
     }
});
karim79
I like the simplicity of this!
Would that actually work? $(this) would be a collection of one object, so is(':last') would evaluate to true everytime.
Frank Schwieterman