DA.
DA.

Reputation: 40673

less verbose way to chain jquery events that have to wait for animations?

Chaining is great in jQuery, but it chains the trigger of each event and doesn't wait for the previous event to finish. This is noticeable primarily when animating.

As such, the workaround I've seen is to use call back functions. The only drawback is if, say, you have 4 things that you want to animate in succession.

Admittedly, this is probably something you don't want to do very often, but when you do, the markup seems to get a bit verbose. Example (pseudocode):

element.animate(fast, callBackFunction1(element1,element2,element3);

function callBackFunction1(element1,element2,element3){
    element1.animate(fast, callBackFunction2(element2,element3));
};

function callBackFunction2(element2,element3){
    element2.animate(fast, callBackFunction3(element3));
};

function callBackFunction3(element3){
    element3.animate(fast);
};

In that situation, is that the best/most succinct way to go about things?

Upvotes: 1

Views: 1585

Answers (2)

joshperry
joshperry

Reputation: 42227

var animElements = [
    element,
    element1,
    element2,
    element3,
];

function animateChain(elements) {
    if(elements.length > 0) {
        var element = elements.pop();
        element.animate("fast", function(){ animateChain(elements); });
    }
}

animateChain(animElements);

Upvotes: 1

PKKid
PKKid

Reputation: 3076

Try the following.. :)

element.animate(fast, function() {
    element1.animate(fast, function() {
        element2.animate(fast, function() {
            element3.animate(fast);
        });
    });
});

Upvotes: 5

Related Questions