2

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.

4 Answers 4

2
$(document).ready(function(){
    $('.container .some-div').each(function(i){
        $(this).delay(i*500).animate({opacity: 1},1000);
    });
});

DEMO HERE

Sign up to request clarification or add additional context in comments.

Comments

2

Simply loop over that class, use index to set delay

$('.some-div').each(function (i) {
    $(this).delay(i * 100).animate({ opacity: '1'});
});

DEMO

Comments

1

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);
});

JS FIDDLE

Comments

1

Working Example

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.

1 Comment

This answer still requires editing the JavaScript (add the div's ID) each time an HTML tag is added to .container.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.