Mr. Developer Mr. Developer - 7 months ago 32
Javascript Question

Jquery each() function increment by half

I'm trying to add

0.5
increment after each iteration using jquery
each()
function. I have to add
animatoin-delay
property on
li
which value should increase (
0.5
) that i can animate them on document load.

HTML



<ul class="social-link">
<li></li>
<li></li>
<li></li>
<li></li>
</ul>


JS



$('ul.social-link li').each(function(i){
plus = i - 0.5;
$(this).addClass('animated fadeIn').css('animation-delay',plus+'s');
});


I have tried above code, but it does working after first iteration, on first iteration its given
0.5
but after that its adding (1.5, 2.5, 3.5) 1 instead of 0.5. I know my logic is not correct. Can any one guide me regarding this that its possible or not using
each()
function. I can do it using
css
but it will be good if done using jquery. I will appreciate if someone guide me. Thank You

Answer

In your code, i is the index of the collection your selector is returning. So, 1-0.5, 2-0.5, 3-0.5, etc. If I'm understanding you correctly, you want to add .05 every time through, so declare plus outside of .each() like so: var plus = 0; and increment it like so inside the loop: plus += 0.5. It'll increment like this: .5, 1, 1.5, 2, 2.5, etc.