Jquery - defer callback until multiple animations are complete

后端 未结 6 424
情书的邮戳
情书的邮戳 2020-12-09 03:03

I need a callback to execute once after multiple elements have finished animating. My jquery selector is as follows:

$(\'.buttons\').fadeIn(\'fast\',function         


        
相关标签:
6条回答
  • 2020-12-09 03:18

    An alternative to @Ross's answer that will always trigger the callback on the last button to fade in (which may or may not be the last button that was told to animate) could be:

    var buttons = $(".buttons");
    var numbuttons = buttons.length;
    var i = 0;
    
    buttons.fadeIn('fast', function() {
        i++;
        if(i == numbuttons) {
            //do your callback stuff
        }
    });
    
    0 讨论(0)
  • 2020-12-09 03:29

    jQuery introduced a promise in version 1.6 and is far more elegant than adding counters.

    Example:

    // Step 1: Make your animation
    $(".buttons").each(function() {
        $(this).fadeIn("fast");
    });
    
    // Step 2: Attach a promise to be called once animation is complete
    $(".buttons").promise().done(function() {
        // my callback
    });
    
    0 讨论(0)
  • 2020-12-09 03:30
    var $buttons = $('.buttons');
    
    $buttons.each( function (index) { 
        if ( index == $buttons.length - 1 ) {
            $(this).fadeIn('fast',function() {
               // my callback
            });
        } else {
            $(this).fadeIn('fast');
        }
    });
    

    Untested but this should apply the callback to the last button only.

    0 讨论(0)
  • 2020-12-09 03:36

    The idea behind my solution is to keep a counter. Whenever an animation finishes, you simply increment this counter, thus you can see when you are at last button. Remember to set the counter back to zero when everything is done, because you might want to repeat this (hide them again, and show them again).

    var $buttons=$('.buttons'),
        button_n=$buttons.length,
        button_counter=0;
    $buttons.fadeIn('fast', function () {
        if (button_counter==button_n-1) {
            alert('It is all done!');
            button_counter=0;
        } else {
            button_counter++;
        }
    });
    
    0 讨论(0)
  • 2020-12-09 03:40

    For collecting unrelated element animations into a single callback you can do this:

    $.when(
        $someElement.animate(...).promise(),
        $someOtherElement.animate(...).promise()
    ).done(function() {
        console.log("Both animations complete");
    });
    
    0 讨论(0)
  • 2020-12-09 03:41
    onClickBtnEdit = function(){
        var $EditDel = $($btnEdit).add($btnDel);
        var btns = $EditDel.size();
    
        $EditDel.fadeOut("def",function(){                   
            btns--;
            if(btns===0){
                $($btnSave).add($btnCancel).fadeIn("slow");
            }
        });
    };
    
    0 讨论(0)
提交回复
热议问题