Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How create a chained delayed animation sequence in jQuery?

Consider having the following objects:

<div id="d1"><span>This is div1</span></div>
<div id="d2"><span>This is div2</span></div>
<div id="d3"><span>This is div3</span></div>
<div id="d4"><span>This is div4</span></div>
<div id="clickhere"><span>Start animation</span></div>

And consider that I would like to apply, using jQuery, an animation on each of the four element listed before.

What I have now

Consider the following code applied in the head section if the page:

function start_anim() {
  $("#d1").animate({top:"-50px"},1000,function(){}); // Animating div1
  $("#d2").animate({top:"-50px"},1000,function(){}); // Animating div2
  $("#d3").animate({top:"-50px"},1000,function(){}); // Animating div3
  $("#d4").animate({top:"-50px"},1000,function(){}); // Animating div4
}
$(document).ready($('#clickhere').click(start_anim));

This fragment of script will cause a synchronous translation of the four divs when the event click is fired.

What I would like to have

However I would like to have the first div move first, then I would like to have the second div move when the first div's animation has reached the 50%. The same for the third and the last div.

How can I reach this? Thankyou

like image 699
Andry Avatar asked Jan 12 '23 02:01

Andry


1 Answers

Something like:

$("#d1").animate({top:-50}, 1000);
$("#d2").delay(500).animate({top:-50}, 1000);
$("#d3").delay(1000).animate({top:-50}, 1000);
$("#d4").delay(1500).animate({top:-50}, 1000);

Or even better:

var duration = 1000;

$('#d1,#d2,#d3,#d4').each(function(i) {
   $(this).delay( i*(duration/2) ).animate({top:-50}, duration);
});
like image 77
David Hellsing Avatar answered Jan 17 '23 15:01

David Hellsing