RobJShillito RobJShillito - 1 month ago 13
jQuery Question

jQuery: How to trigger a callback function after `animate()` function completes

I would like to be able to use a callback in a stack of events, but not at the end. I tried to do it, but it seems the code escapes any effects after the callback has been called.

$(this).animate({//animate image
top:0
}, aniTime)

.delay(1000, function(){

//some code

})

.animate({//animate image
top:250
}, aniTime)


Is there a way to do this or is it not possible/best practise ?

Answer Source

You can achieve this effect by using the complete callback parameter of animate. This will run it's contents on completion of the first animate at the same time as the delay time begins.

Example:

$(this).animate({//animate image
        top:0
    }, aniTime,
    // complete callback follows:
    function(){
        $('otherElement').fadeOut(200);
    })
    .delay(1000)
    .animate({//animate image
        top:250
    }, aniTime)