5

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

3
  • Are you sure you want to call the strart_anim() function when the #clickhere element is clicked? You are not passing the function but its return value.
    – Hidde
    Oct 20, 2013 at 14:08
  • api.jquery.com/delay Oct 20, 2013 at 14:10
  • @Hiddle: Sorry, you are right, I just mistyped :P
    – Andry
    Oct 20, 2013 at 14:14

1 Answer 1

11

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);
});
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.