2

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);
}
Ivan Ferić
  • 4,725
  • 11
  • 37
  • 47
user1943442
  • 198
  • 4
  • 17

1 Answers1

7

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() {
    ...
});
Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • p.s. use `this.id` instead of `$(this).attr('id')` – Alnitak Jan 02 '13 at 17:04
  • I have used `promise` and `done`, if I have for example 10 elements within a jQuery collection, it takes 10 * duration and then callback is executed, is there any other way? – Ram Jan 02 '13 at 17:11
  • @undefined it shouldn't do that. Have you got a jsfiddle to demonstrate that? – Alnitak Jan 02 '13 at 17:16
  • Unfortunately no, actually I had a project with many animations, this doesn't happen always. never mind, thanks. – Ram Jan 02 '13 at 17:26
  • @undefined see the caveat in the docs for `.promise()` that talk about what happens if you use it on an element that is subsequently removed before the promise is resolved. – Alnitak Jan 02 '13 at 17:31