1

I have checked everywhere looking for a solution to this, and have not been able to figure it out. The solution eludes me.

For complicated reasons, I can't simply change the margin/padding swap in CSS, so I'm trying to add style="z-index:5;" in the first div, and then style="z-index:4;" in the second div, etc. so that the last element on the page has the lowest z-index, and each element going toward the top adds one, so it always remains on top if there is any overlap, which is the case with some links that currently sit below the subsequent sibling element.

Stripped down sample code below: I know my counter is working, but the value of the incrementer (z) is not passing to the .css method in the for loop. Any suggestions?

<style>
.subsection {
    margin-top: -80px;
    padding-top: 80px;
    position: relative;
}
</style>

<script>
    var set_zindex = function(){
        var subsection = $('.subsection');
    var subsections = subsection.length;
    var z;
    for ( z=subsections; z >=0; z-- ) {
        subsection.css('z-index', z );
    }
}
set_zindex();
</script>

<html>
<div class="subsection">some content</div>  //add style="z-index:5:
<div class="subsection">some content</div>  //add style="z-index:4:
<div class="subsection">some content</div>  //add style="z-index:3:
<div class="subsection">some content</div>  //add style="z-index:2:
<div class="subsection">some content</div>  //add style="z-index:1:
</html>
Brett Gregson
  • 5,867
  • 3
  • 42
  • 60

2 Answers2

3

You are working with a jQuery collection (var subsection). You need to go over each item in that collection separately.

Something like:

subsection.each(function(i){
  $(this).css('z-index', subsection.length-i);
});
Jack
  • 9,448
  • 3
  • 29
  • 33
  • How would you incrementally decrease the z-index count with a starting point element having a z-index of 999? Using the code above, it assumes a starting z-index of 1. – Steve Jun 25 '13 at 19:10
  • The code above assumed a starting z-index of subsection.length. If you wanted it to be 999, then replace `subsection.length` with `999`. – Jack Jun 27 '13 at 17:25
0

You should use z -= 1 in a for loop. Sometimes things get screwy otherwise. See here

And iterate with each.

subsection.each
  (
    function(i) {
         $(this).css('z-index',subsections-i);
    } 
  )
;
Community
  • 1
  • 1
Cris Stringfellow
  • 3,714
  • 26
  • 48