Oliver Bayes-Shelton
Oliver Bayes-Shelton

Reputation: 6292

Could you explain this jQuery code for me

Could any one explain how this jQuery code snippet works ?

This is the html

<div class="faded">Div 1</div>
<div class="faded">Div 2</div>
<div class="faded">Div 3</div>
<div class="faded">Div 4</div>
<div class="faded">Div 5</div>
<div class="faded">Div 6</div>
<div class="faded">Div 7</div>


$(".faded").each(function(i) {
    $(this).delay(i * 400).fadeIn();
});

Im kinda stuck on figuring out how this section works

$(this).delay(i * 400).fadeIn();

Upvotes: 1

Views: 149

Answers (7)

Mark
Mark

Reputation: 8291

Fades in the div one after the other with a delta of 400ms

Here is the official documentation of the delay function:

http://api.jquery.com/delay/

Upvotes: 2

blue112
blue112

Reputation: 56442

$(this).delay(i * 400).fadeIn();

delay(i * 400) will wait for 400ms x i, so it'll wait 400ms for the first, 800ms for the second...

Then, the block will fadeIn.

Upvotes: 2

Fosco
Fosco

Reputation: 38526

The each function iterates through all of the elements matching your selector (class of 'faded').. The i parameter is the index number of the element.

Since they are in order like this, each one is delayed by an additional 400 seconds so they fade in one at a time.

You can experiment with it here if you like: http://jsfiddle.net/gfosco/Wx6Qr/

Upvotes: 2

Rebecca Chernoff
Rebecca Chernoff

Reputation: 22605

The easiest way to explain it would be create a jsfiddle with it so that you can see it realtime.

When you .each over the array, i will be the index of the current element in the array. So, it is just fading each element a little bit after the element before it.

Upvotes: 1

Sarfraz
Sarfraz

Reputation: 382696

It is equivalent to this:

$(this).delay(1 * 400).fadeIn();
$(this).delay(2 * 400).fadeIn();
$(this).delay(3 * 400).fadeIn();
$(this).delay(4 * 400).fadeIn();
$(this).delay(5 * 400).fadeIn();
// as long as there are elements in the wrapped set

So basically each div is shown after a delay of value of i multiplied by 400 making each div show later than first.

Upvotes: 3

Šime Vidas
Šime Vidas

Reputation: 185933

The DIVs will fade in one-at-a-time every 0,4 seconds...

Upvotes: 1

kkyy
kkyy

Reputation: 12460

The code loops over the divs and delays the fadeIn function based on their order. That is, first div fades in after 1 * 400ms delay, second 2 * 400ms delay etc.

Upvotes: 4

Related Questions