Question

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?

Was it helpful?

Solution

Try the following.. :)

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

OTHER TIPS

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top