login
jQuery fadeIn() demo 2 posted: Wed 2013-07-17 20:08:25 tags: tech
Consider the following:
$("#div1").fadeIn("slow", function(){
  $("#div2").fadeIn("slow", function(){
    $("#div3").fadeIn("slow", function(){
      $("#div4").fadeIn("slow");
    });
  });
});

It works, but the code is ... I don't want to say "ugly", because it's perfectly comprehensible to a jQuery novice. Rather, let's say it doesn't scale in dynamic content scenarios. This guy blogged two three scalable ways to accomplish the same thing back in mid-2008:

1. Self-executing callback chain

(function showDiv(elem){
  elem.fadeIn('slow',function(){
    $(this).next().length && showDiv($(this).next());
  });
})( $("div.subDiv:first") );

2. Custom event triggering

$('div.subDiv')
  .bind('showDiv',function(e) {$(this).fadeIn('slow',function(){
    $(this).next().length && $(this).next().trigger("showDiv");
  })})
  .eq(0)
    .trigger('showDiv');

and the chosen "winner",
3. Self-executing callback chain on any arbitrary jQuery object

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