$(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.
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 animate() method? Yes, almost!
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With