Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the highest z-index using jQuery

I have a number of div elements with different z-index. And I want to find the highest z-index among these divs - how can I achieve it?

CSS:

#layer-1 { z-index: 1 } #layer-2 { z-index: 2 } #layer-3 { z-index: 3 } #layer-4 { z-index: 4 } 

HTML:

<div id="layer-1">layer-1</div> <div id="layer-2">layer-2</div> <div id="layer-3">layer-3</div> <div id="layer-4">layer-4</div> 

I don't think this line can find the highest z-index though.

var index_highest = parseInt($("div").css("zIndex")); // returns 10000 
like image 827
Run Avatar asked Apr 15 '11 18:04

Run


People also ask

What is the highest Z index?

The maximum range is ±2147483647. In CSS code bases, you'll often see z-index values of 999, 9999 or 99999. This is a perhaps lazy way to ensure that the element is always on top. It can lead to problems down the road when multiple elements need to be on top.

Is higher z index on top?

It's super useful, and honestly a very important tool to know how to use in CSS. Unfortunately, z-index is one of those properties that doesn't always behave in an intuitive way. It seems simple at first- a higher z-index number means the element will be on top of elements with lower z-index numbers.

What is Z index in jquery?

The z-index specifies the order of stack for an element. The element which has the highest order of stack always appear in front of the element which have the lowest order of stack. The z-index uses on positioned elements like position: absolute, position: relative, position: sticky or position: fixed.


1 Answers

Note that z-index only affects positioned elements. Therefore, any element with position: static will not have a z-index, even if you assign it a value. This is especially true in browsers like Google Chrome.

var index_highest = 0;    // more effective to have a class for the div you want to search and  // pass that to your selector $("#layer-1,#layer-2,#layer-3,#layer-4").each(function() {     // always use a radix when using parseInt     var index_current = parseInt($(this).css("zIndex"), 10);     if(index_current > index_highest) {         index_highest = index_current;     } }); 

JSFiddle demo

A general jQuery selector like that when used with an option that returns one value will merely return the first So your result is simply the z-index of the first div that jQuery grabs. To grab only the divs you want, use a class on them. If you want all divs, stick with div.

like image 54
justkt Avatar answered Sep 20 '22 23:09

justkt