Hady
Hady

Reputation: 2674

Start animating div when the other div animations completes

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 is:

  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.

Upvotes: 1

Views: 291

Answers (3)

Hady
Hady

Reputation: 2674

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.

Upvotes: 1

Paolo Bergantino
Paolo Bergantino

Reputation: 488434

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

$('#div1').animate({...}, 1000, 'linear', function() {
    $('#div2').animate({...}, 1000);
});

Upvotes: 6

strager
strager

Reputation: 90022

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

div1.animate({ ... }, 'slow', 'linear', function() {
    div2.animate({ ...}, ...);
});

Upvotes: 1

Related Questions