tobypitman.com

JQuery: Fade elements sequencially without chaining

Here’s a useful trick for fading similar elements sequencially without having to chain the effects. In the first example I have 5 divs that I want to fade in one after the other. Instead of giving them all unique ID’s and chaining the fade effects like this….

$("#box1").fadeIn("slow", function(){
  $("#box2").fadeIn("slow", function(){
    $("#box3").fadeIn("slow", function(){
      $("#box4").fadeIn("slow", function(){
        $("#box5").fadeIn("slow");
      });
     });
   });
});



…… you can instead give them a class of ‘box’ and find the amount using .length; and use an if statement to loop through the until all the relevant elements are visible using a callback function.

var i = 0
var n = $(".box").length;
       
function showbox() {
       
    if(i <= n){
           
    $(".box").eq(i).fadeIn(600, function(){ i++; showbox(); });
             
            }        
        } showbox();



It’s a lot more efficient code wise and produces the same effect. Here’s the same thing but using a ‘click’ event to trigger the function.

var j = 0
var a = $(".list").length;
       
    $("#trigger").click(function showlist(){
               
        if(j <= a){            
        $(".list").eq(j).fadeIn(200, function(){ j++; showlist(); });
             
         }       
    });



Might be a nice effect for a menu? I was going to use it to fade in the posts on the blog homepage but IE7 can’t render one transparent PNG over another when faded. It comes out looking like a jaged GIF with the top PNG’s transparent pixel looking black instead. Once again IE ruins everything!!!

View Demo

Posted on Saturday, December 13th, 2008 at 10:07 pm.

Filed under jQuery.

2 Responses to “JQuery: Fade elements sequencially without chaining”

  1. MARCO says:

    VERY VERY GOOD SCRIPT. I WAS LOOKING FOR IT!!!!!! PROBABLY I USE IT ON THIS SITE http://WWW.SETTECOLORI.IT. THANKS. MARCO FROM ROME.

    • MARCO says:

      the only thing is that in internet explorer 8 doesn’t work properly:-( as you check in the web site i’m doing. check with ff, safari, chrome and……ie8:-(. let me know if you can fix the bug.

Don't be shy, leave a comment