Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining jQuery animations that affect different elements

$(document).ready(function() {
    $("#div1").fadeIn("slow");
    $("#div2").delay(500).fadeIn("slow");
    $("#div3").delay(2000).fadeIn("slow");
    $("#div4").delay(8000).fadeIn("slow");
});

This is my current setup but I feel like this isn't the best way to write this. I can't find any examples on how you would write this better for timing. Any help? I'd appreciate it.

I should also add that the timing of each element isn't consistent.

like image 582
Tom Avatar asked Nov 16 '10 19:11

Tom


People also ask

Which function is used to chain animations in jQuery?

jQuery | chaining() With jQuery, we can use do chaining which means to chain together multiple methods in a single statement on a single element. We have been using a single statement at once, but now using the chaining method we can bind multiple methods to make the code short.

Is it possible to manipulate all CSS properties with the jQuery animate method?

Is it possible to manipulate ALL CSS properties with the animate() method? Yes, almost!

Which jQuery method can be used to animate changes in CSS properties?

The animate() method performs a custom animation of a set of CSS properties. This method changes an element from one state to another with CSS styles. The CSS property value is changed gradually, to create an animated effect.

Can the jQuery animate () method be used to animate any CSS property?

jQuery animate() MethodThe animate() method is typically used to animate numeric CSS properties, for example, width , height , margin , padding , opacity , top , left , etc. but the non-numeric properties such as color or background-color cannot be animated using the basic jQuery functionality.


1 Answers

fadeIn takes a callback as its second parameter. That callback is executed as soon as the animation is complete. If you want the elements to fade in sequentially, you could chain the callbacks:

$(document).ready(function() {
    $("#div1").fadeIn("slow", function(){
        $("#div2").fadeIn("slow", function(){
            $("#div3").fadeIn("slow", function(){
                $("#div4").fadeIn("slow");
            });
        });
    });
});

This could be re-written using an array of selectors and a single method, if you felt like it:

var chain = function(toAnimate, ix){
    if(toAnimate[ix]){
        $(toAnimate[ix]).fadeIn('slow', function(){ chain(toAnimate, ix + 1 )});
    }
};

$(document).ready(function(){
    chain(['#div1', '#div2', '#div3', '#div4'], 0);
});

See this last one in action at JSBin.

like image 71
Dan Davies Brackett Avatar answered Oct 17 '22 15:10

Dan Davies Brackett