views:

185

answers:

3

I am working on a rather complex jquery-to be animation which moves various div's based on different trigger events. To simplify the scenario I am trying to solve, see the following:

  1. I have DIV 1 and DIV 2 on the screen
  2. DIV 1 needs to animate from position A to position B
  3. DIV 2 needs to also animation from position C to position D, however ONLY when DIV 1 reaches position B.

How should I get around doing something like this?

I am thinking I need to use a trigger/event listener mechanism, were DIV 2 goes to sleep, and only gets woke up by an event that gets triggered when DIV 1 reaches position B on the screen.

Is this the best mindset I should have? How do I do this using jQuery.

Much appreciated.

+6  A: 

The animate function lets you specify a callback that is run when the animation finishes:

$('#div1').animate({...}, 1000, 'linear', function() {
    $('#div2').animate({...}, 1000);
});
Paolo Bergantino
I understand and know about animate's callback function. However, I have far too many div's on the screen to nest-animate them in this fashion. I need each div to have their animate function run independently.
Hady
+1  A: 

jQuery has an animate function which accepts a callback. Animate DIV 2 there.

div1.animate({ ... }, 'slow', 'linear', function() {
    div2.animate({ ...}, ...);
});
strager
+1  A: 

I ended up coming up with the following solution which solves my situation:

div1.animate(
   {...},
   'complete' : function() {
      div2.trigger('myStartMove');
   }
);

div2.bind('myStartMove', function(ev){
   div2.animate(
      {...}
   );
});

I found it best to use triggers rather than directly call nested animations in the complete callback. Makes my coding a lot cleaner for the complex animation that I have.

Hady
Note that the first example won't work. "complete" needs to be in another object, so you need to wrap it in curly braces if you want it to pass to animate.
Husky