Reputation: 577
How can I make all the div
elements in a container fade in one after each other without setting a delay for each div
inside the container?
Here is my working jQuery code:
$("#a").animate({opacity: '1'});
$("#b").delay(100).animate({opacity: '1'});
$("#c").delay(200).animate({opacity: '1'});
$("#d").delay(300).animate({opacity: '1'});
$("#e").delay(400).animate({opacity: '1'});
Fiddle: http://jsfiddle.net/f9poom60/2/
Now if I want to add one more div
, I have to add it with a delay in my JavaScript and I have to add it in CSS. I'm pretty sure it can be done in a more simple way.
Upvotes: 2
Views: 867
Reputation: 3089
One way you could do it would be to use an each()
loop and fade them in:
Here you go:
$(document).ready(function() {
$('#word1, #word2, #word3, #word4, #word5').each(function(fadeInDiv){
$(this).delay(fadeInDiv * 500).fadeIn(1000);
});
});
Note I'm supplying a parameter, fadeInDiv
, which will increment for each of the three elements (returns 0, 1, 2)
and multiplying that by the delay, so you will get the delay incrementing accordingly (0, 500, 1000)
etc.
Upvotes: 1
Reputation: 24001
$(document).ready(function(){
$('.container .some-div').each(function(i){
$(this).delay(i*500).animate({opacity: 1},1000);
});
});
Upvotes: 2
Reputation: 749
A better way to do this would be using jQuery's .each()
. This allows you to loop through any children of .container
. Change 400*index
to speed up or slow the delay.
$(".container").children().each(function(index) {
$(this).delay(400*index).animate({opacity:'1'},100);
});
Upvotes: 1
Reputation: 171690
Simply loop over that class, use index to set delay
$('.some-div').each(function (i) {
$(this).delay(i * 100).animate({ opacity: '1'});
});
Upvotes: 2