jrrdnx
jrrdnx

Reputation: 1585

Callback animation to begin only after ALL children have finished animating

I have a div wherein I would like to fade all of the child elements out at once, but fade in a new element but only after all children have completed fading out. Using my current code below, the #Message div starts fading in after the first child element and is actually placed after the last child. Once the last child fades out completely, the #Message div then "jumps" up into position. I want to avoid this "jump".

$('#DIV').children().fadeOut("slow", function() {
    $('#Message').fadeIn("slow");
});

How can I make certain the fadeIn() animation doesn't begin until fadeOut() is complete on ALL child elements of #DIV?

Edit: I should note that my #Message div is located inside of #DIV.

Upvotes: 5

Views: 2286

Answers (2)

Ariel
Ariel

Reputation: 26783

$('#DIV').children().fadeOut("slow", function() {
    if($('#DIV').children().filter(':animated').length == 1) $('#Message').fadeIn("slow");
});

Basically count how many are still animating, and when there is only one left, run the callback.

This also makes your callback run just once, not once per element.

Upvotes: 0

rkw
rkw

Reputation: 7297

You'll want to use deferred objects specifically for scenarios like this. The easy part is that animations already create deferred objects by default: http://jsfiddle.net/rkw79/zTxrt/

$.when(
    $('#DIV').children().each(function(i,o) {
        $(o).fadeOut((i+1)*1000);
    })
)
.done(function() {
    $('#Message').fadeIn("slow");
});

Upvotes: 10

Related Questions