tags:

views:

24

answers:

2

Sample jquery. Assume $cog is a cached selector of multiple items.

$cog.fadeOut('slow',function(){
    alert('hey');
})

In that example, of $cog is a jQuery object of 4 DOM elements, the above will fade each element out one by one, and trigger an alert each time on the callback (4 alerts).

I'd like to only call the alert when all 4 elements are done with their fadeOut function.

This:

$cog.fadeOut('slow',function(){
})
alert('hey');

when run, will show an alert, then the $cog elements disappear (I'm guessing due to timing issues with the fadeOut animation)

Is there a way when calling a function against multiple DOM objects in a jQuery object to know when it's done with the last item?

+2  A: 

You can simply count the callbacks back in.

Try this:

var remaining=$cog.length;
$cog.fadeOut('slow',function(){
    if((--remaining)==0)alert('hey');
})
spender
I get a 'remaining is not defined' error in firebug with that.
DA
Written exactly as above, with no typos? I've not tested, but it's definitely in scope and captured by the callback function.
spender
ack. Sorry, missed the variable declaration. I'm still a bit fuzzy on the shorthand way of writing if statements. I couldn't get that specific if statement to work, but this does: remaining = remaining-1;if(remaining==0){alert('hey');}
DA
An equivalent (and for my eyes, clearer) if statement would be:if (!remaining--) alert('hey');... personal choice :P
Matt
Should have been --remaining. Sorry bout that. I've corrected the code.
spender
+1  A: 

Try this example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;
<script type="text/javascript">
$(function() {
  var items = $("li");
  $("#btn").click(function() {
    (function() {
      var items = $("li");
      items.fadeOut("slow", function() {
        items = items.not(this);
        console.log(items.length);
        if (items.length == 0) {
          alert("all done");
        }
      });
    })();
  });
});
</script>
<style type="text/css">
</style>
</head>
<body>
<input type="button" id="btn" value="Fade Out">
<ul>
  <li>one</li>
  <li>two</li>
  <li>three</li>
</ul>
</body>
</html>
cletus
thanks, cletus. That's a good idea, too!
DA