2

How would I incrementally decrease the z-index on a set of div elements using jQuery starting with an index of 999.

I have already seen other questions about incrementally decreasing z-index but it doesn't have a starting z-index for the first element. Modified code from that post is below:

$('div.count').each(function(i){
  $(this).css('z-index', $(this).length-i);
});

End result should look like:

<div class="count" style="z-index:999;"></div>
<div class="count" style="z-index:998;"></div>
<div class="count" style="z-index:997;"></div>
Community
  • 1
  • 1
Steve
  • 4,694
  • 11
  • 43
  • 61

5 Answers5

2

Tell it where to start, and subract one on every iteration :

var start = 999;

$('div.count').each(function(i){
  $(this).css('z-index', start--);
});

or use the index

$('div.count').each(function(i){
  $(this).css('z-index', 999 - i);
});
adeneo
  • 303,455
  • 27
  • 380
  • 377
1

That will give you a wring z index.Declare a global variable and decrement in loop.

var subsection = 999;   
$('div.count').each(function(i){
  $(this).css('z-index', subsection --);
});
Suresh Atta
  • 118,038
  • 37
  • 189
  • 297
1

You can use the index method..

var count = $('div.count').length; 
$('div.count').each(function(i){
  $(this).css('z-index', count - $('div.count').index(this));
});

or

var count = $('div.count').length; 
$('div.count').each(function(i){
   $(this).css('z-index', count - i);
});
Sushanth --
  • 54,565
  • 8
  • 62
  • 98
1
var start = 999;
$('div.count').CSS('z-index', function () {
    return start--;
});

References:

David Thomas
  • 240,457
  • 50
  • 366
  • 401
1

Following Code will work properly:

jQuery('div.count').each(function(i){
  jQuery(this).css('z-index', 999-i);
});

The z-index of first element will be 999 and the 999th will be 0...

Atrox111
  • 527
  • 4
  • 17