Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Waiting for the fadeOut to complete before running fadeIn

Tags:

jquery

I was wondering if the is any way to wait until the fadeOut is complete before the fadeIn commences, as when i run the following code, it places one div under the other, then when its faded out it moves up ... looks a little ugly.

Code is as follows:

$('.sidebarform').fadeOut('slow');
$('.sidebarsuccess').fadeIn('slow');
like image 461
BigJobbies Avatar asked Nov 21 '11 06:11

BigJobbies


3 Answers

The fadeOut function has a callback that it executes when the animation is done:

$('.sidebarform').fadeOut('slow', function() {
    $('.sidebarsuccess').fadeIn('slow');
});
like image 177
mu is too short Avatar answered Oct 11 '22 11:10

mu is too short


Another option is using promise which will wait for all pending animations on .sidebarform to complete first even if they were started elsewhere:

$('.sidebarform').fadeOut('slow').promise().done(function() {
    $('.sidebarsuccess').fadeIn('slow');
});
like image 38
kravits88 Avatar answered Oct 11 '22 10:10

kravits88


I am using jQuery's Queues - allows you to put anything on the fx stack (and canceling works with it as well, no need for a finalizing .promise()):

$('.sidebarform').fadeOut('slow').queue(function(done) {
    $('.sidebarsuccess').fadeIn('slow');
    done();
}) .... other chained effects

if no further effects are used, done() can be removed. .queue() will hold the stack until done() is called - useful for async execution. It will not wait for fadeIn.

This will force the fx stack to wait for fadeIn as well (just as an additional example):

$('.sidebarform').fadeOut('slow').queue(function(done) {
    $('.sidebarsuccess').fadeIn('slow', done);
}) .... other chained effects kicking in after fadeIn

The queue will only continue, when the fadeIn completes and calls done as its callback - which is the queues one. The stack sees this as one entry.

like image 34
BananaAcid Avatar answered Oct 11 '22 12:10

BananaAcid