Daniel Pendergast Daniel Pendergast - 2 months ago 12
CSS Question

Incremental z-index in jquery

I have a navigation bar and I need to always keep the current one on top. I came up with this code, but I don't know why it's not working:

$(this).find('ul.sub_nav').css('z-index', function(index) {
return index++;
});


I inspect it in chrome and all it shows is
<ul class="sub_nav" style="z-index: 0;">
no matter how many times I try it.

It has an initial
z-index
of 1, just FYI.







What I resolved:

var zIndex = 1;

$(document).ready(function() {
$('ul.top_nav > li').hover(function() {
zIndex++;
$(this).find('ul.sub_nav').css('z-index', zIndex);
});
});


A much simpler solution with JS.

Answer

I believe you should do this instead, if you want each element to have a zIndex greater than previous elements in a specific set.

var subs  = $(this).find('ul.sub_nav');
var index = subs.eq(0).css('z-index');
subs.gt(0).each(function() {
    $(this).css('z-index', ++index);
});