Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronous animations in jQuery, not using callbacks?

I can't use callbacks because I have a scenario like this (pseudo-code):

$('.box').on('click', function() {
    $('.expanded-box').animate({
        // shrink it
    });

    $(this).animate({
        // grow it
        $(this).addClass('expanded-box');
    });
});

I can't put the expansion animation within the callback for the expanded-box growth animation because it may not always happen. But I need the second animation to wait till the previous one is done. How can I do this?

like image 416
CaptSaltyJack Avatar asked Feb 27 '12 20:02

CaptSaltyJack


1 Answers

Since jQuery 1.6, you can use promise() to obtain a Promise object that will be resolved when all animations on a given element have completed. In addition, the documentation says:

Using .promise() on a collection with no active animation returns a resolved Promise.

Therefore, it's well-suited to your use case, and you can write:

$('.box').on('click', function() {
    var $this = $(this);
    $('.expanded-box').animate({
        // shrink it
    }).promise().done(function() {
        $this.animate({
            // grow it
        }).addClass('expanded-box');
    });
});
like image 116
Frédéric Hamidi Avatar answered Nov 15 '22 07:11

Frédéric Hamidi