Search code examples
jqueryanimationrandommouseentereasing

Trigger an event after all of the animations from current function completed


I've been trying to get a function to trigger only after all of the element's .animate() functions have been completed including the delay and easing.

I've tried a few different methods with no luck, any ideas?

  $("#inner_work").on("mouseenter", ".activeBox", function(){
        var thisBox = $(this).attr('id');
        $("#inner_work [class^='workBox_']").each(function(){
            if($(this).attr('id') != thisBox){
                $(this).stop().delay(randomEasing(200,800)).animate({
                    opacity:0
                }, randomEasing(200,700));
            } else {
                $(this).stop().animate({
                    opacity:1
                }, 'fast');
            }
        }); 
  });

How do I trigger an event AFTER all the animation has been completed?

randomEasing is just this function to make it randomly staggered

function randomEasing(from,to)
{
    return Math.floor(Math.random()*(to-from+1)+from);
}

Solution

  • You can use deferred objects and request a .promise() to register a callback which will be invoked only when all animations on every element within the collection have completed:

    $("#inner_work [class^='workBox_']").promise().done(function() { 
         ...
    });
    

    This can be chained with your existing code:

    $("#inner_work [class^='workBox_']").each(function() {
        // your existing animation code
    }).promise().done(function() {
        ...
    });