Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery multiply this.index

Trying to write a simple jQuery function that will multiple the index of an object by 20 and assign that value as a CSS top to the object. So if there are 5 objects, the top would have a top value of 20, the second would have a value of 40, third would be set to 60, and so on. This is what I have:

$('ul.nav li').each(function(){
    var $n = $('ul.nav li').index(this);
    $(this).css('top', 20 * n );
});

What am I doing wrong?

like image 733
colindunn Avatar asked Mar 18 '26 07:03

colindunn


1 Answers

index is already provided by $.each:

$("ul.nav li").each(function(index){
  $(this).css( "top", 20 * ++index );
});

The problem with your code was that you were creatin $n, but using n (note the abandoned $).

You could also use implicit looping:

$("ul.nav li").css("top", function(i){
  return 20 * ++i;
});
like image 87
Sampson Avatar answered Mar 19 '26 20:03

Sampson