tags:

views:

28

answers:

2

I need some help on this on how can I animate the following:

If box1 done fading in 2000ms then that is the time to start animate the box2 the box3 and box4

$(document).ready(function(){
  $('#box1').fadeIn(2000);
  $('#box2').fadeIn(2000);
  $('#box3').fadeIn(2000);
  $('#box4').fadeIn(2000);
});

How can i do this, or give me some link. I am noob in jquery

Thank you all

+3  A: 
$(document).ready(function(){
  $('#box1').fadeIn(2000, function() {
    $('#box2').fadeIn(2000, function() {
      $('#box3').fadeIn(2000, function() {
        $('#box4').fadeIn(2000);
      })
    })
  });
});

The animation functions take a second argument, which is a function that is called on completion. You can use this to chain animations.

Though you may want to set this up in a way that it recursively calls a method where you pass in the box id, and it sets up the next in the chain until they are all faded in. Unless all you ever have is 4 boxes, then the above code is fine.

Squeegy
+3  A: 

The question's a but unclear, but you can use .delay() to simplify this:

$(function() {
  $('#box1').fadeIn(2000);
  $('#box2').delay(2000).fadeIn(2000);
  $('#box3').delay(2000).fadeIn(2000);
  $('#box4').delay(2000).fadeIn(2000);
});

See it in action here. If you meant one then another, then another, just change the delay, like this:

$(function() {
  $('#box1').fadeIn(2000);
  $('#box2').delay(2000).fadeIn(2000);
  $('#box3').delay(4000).fadeIn(2000);
  $('#box4').delay(6000).fadeIn(2000);
});

See it in action here. Or, shorten it a bit with .each() using the index parameter it passes to the callback, like this:

$(function() {
  $('#box1, #box2, #box3, #box4').each(function(i) {
    $(this).delay(2000*i).fadeIn(2000);
  });
});

See it in action here. Or, improve it further, giving them a class so it's more extensible, like this:

$(function() {
  $('.box').each(function(i) {
    $(this).delay(2000*i).fadeIn(2000);
  });
});

Test that version here :)

Nick Craver
Thank you so much. This is what i'm looking. =)
Jordan Pagaduan
Actually that last example with each is pretty cool. Good idea. If it used a class instead of ids it could be quite extensible to any number of elements. Nice.
Squeegy
@Squeegy - absolutely! Was getting to adding that :) Takes me a bit to make the example pages
Nick Craver