Synchronized animation in jQuery without using callbacks?

I cannot use callbacks because I have a script like this (pseudo code):

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

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

I cannot put extension animations in a callback for growth animations expanded-box, because this may not always happen. But I need a second animation to wait until the previous one is complete. How can i do this?

+5
source share
2 answers

With jQuery 1.6, you can use prom () to get a Promise object that will be resolved when all animations on the given element are complete. In addition, the documentation says:

.promise() .

, :

$('.box').on('click', function() {
    var $this = $(this);
    $('.expanded-box').animate({
        // shrink it
    }).promise().done(function() {
        $this.animate({
            // grow it
        }).addClass('expanded-box');
    });
});
+7

, , . , , , " " :

$('.box').on('click', function() {
    var $this = $(this),
        $exp = $(".expanded-box");

    function grow() {
       $this.animate({
           width: "200px", height: "100px"
       }).addClass('expanded-box');
    }

    if ($exp.length > 0) {
       $exp.animate({
           width: "100px", height: "50px"
       }, grow).removeClass("expanded-box");
    } else {
       grow();
    }        
});​

: http://jsfiddle.net/PXddm/

+1

All Articles