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,946
  • 12
  • 45
  • 62

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
  • 312,895
  • 29
  • 395
  • 388
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
  • 120,458
  • 37
  • 198
  • 307
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 --
  • 55,259
  • 9
  • 66
  • 105
1
var start = 999;
$('div.count').CSS('z-index', function () {
    return start--;
});

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
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