tiffylou
tiffylou

Reputation: 546

Apply z-index descending to li with jQuery

I need to count the li's and then add z-index in reverse order, to look like:

<li style="z-index:3;"></li>
<li style="z-index:2;"></li>
<li style="z-index:1;"></li>

I do not want 0 or negatives on any z-indexes, and it needs to be in reverse order. I would like to use jQuery since I won't know how many li's will be on this list.

Here is what I have so far:

    var numIndex = $("ul.progress li").length + 1;
    $("ul.progress li").each(
      function(numIndex) {
        $(this).css("z-index", numIndex*-1);
    });

Please advise if you know what I am missing.

Upvotes: 4

Views: 993

Answers (3)

Blazemonger
Blazemonger

Reputation: 92943

Did you know you can pass a callback argument to .css()?

var c = $('#list li').length;
$('#list li').css('z-index', function(i) {
    return c - i;
});

http://jsfiddle.net/mblase75/XuSX8/

Upvotes: 4

Dom
Dom

Reputation: 40491

Try something like this:

$(function(){
    var numIndex = $("ul.progress li").length;

    $("ul.progress li").each(function(i){
        $(this).css("z-index", numIndex-i);
    });
});

DEMO: http://jsfiddle.net/dirtyd77/F39WC/

Upvotes: 1

Jai
Jai

Reputation: 74738

You have to take out the .each() function param:

var numIndex = $("ul.progress li").length;
$("ul.progress li").each(function () {
   $(this).css("z-index", numIndex--);
});

Upvotes: 0

Related Questions