Paul Irish

Making the www great

Sequentially Chain Your Callbacks in jQuery - Three Ways

I had a challenge to get four divs to fade in sequentially.

Writing this out the long way is not really my favorite:

1
2
3
4
5
6
7
$("#vehicle1").fadeIn("slow", function(){
  $("#vehicle2").fadeIn("slow", function(){
    $("#vehicle3").fadeIn("slow", function(){
      $("#vehicle4").fadeIn("slow");
    });
  });
});

Ewwww. right?

After some conversation in the #jQuery IRC channel, I present twothree classier ways of accomplishing the same thing:

Self-executing callback chaining

1
2
3
4
5
(function showVehicle(elem){
  elem.fadeIn('slow',function(){
    $(this).next().length && showVehicle($(this).next());
  });
})( $("div.vehicle:first") );

Custom event triggering (via: ajpiano)

1
2
3
4
5
6
$('div.vehicle')
  .bind('showVehicle',function(e) {$(this).fadeIn('slow',function(){
    $(this).next().length && $(this).next().trigger("showVehicle");
  })})
  .eq(0)
    .trigger('showVehicle');
Update 2009.06.15: I’m incredibly impressed with temp01’s solution in the comments. So that’s my recommendation going forward:

Self-executing callback chain on an arbitrary jQuery object (via: temp01)

1
2
3
4
5
(function hidenext(jq){
    jq.eq(0).fadeOut("fast", function(){
        (jq=jq.slice(1)).length && hidenext(jq);
    });
})($('div#bodyContent a'))

Comments