Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the highest z-index within a document no matter what tags they are?

How can I find the highest z-index within a document no matter what tags they are?

I found this code but I tested it and it does not work,

//include jQuery.js --  visit: http://jquery.com/
$(function(){
    var maxZ = Math.max.apply(null,$.map($('body > *'), function(e,n){
           if($(e).css('position')=='absolute')
                return parseInt($(e).css('z-index'))||1 ;
           })
    );
    alert(maxZ);
});

Any better approach to do this?

EDIT:

It seems to work if I change the code to this,

$('body *')

$('body > *') --> is for div only I guess.
like image 945
Run Avatar asked Jul 16 '13 20:07

Run


People also ask

What is Z Index tag?

Z Index ( z-index ) is a CSS property that defines the order of overlapping HTML elements. Elements with a higher index will be placed on top of elements with a lower index. Note: Z index only works on positioned elements ( position:absolute , position:relative , or position:fixed ).

How do you use Z index without absolute positioning?

Yes: use position:relative; z-index:10 . z-index has no effect for position:static (the default).

What is the use of Z Index in HTML?

The z-index CSS property sets the z-order of a positioned element and its descendants or flex items. Overlapping elements with a larger z-index cover those with a smaller one.


2 Answers

This isn't the most efficient solution, but it should work. jsFiddle.

Please note you have to have a position specified in order for the z-index to return a value.

var highest = -999;

$("*").each(function() {
    var current = parseInt($(this).css("z-index"), 10);
    if(current && highest < current) highest = current;
});

alert(highest);
like image 195
Dan Grahn Avatar answered Sep 24 '22 16:09

Dan Grahn


This seems to work:

var maxZ=0;
$('*').each(function(){
    if($(this).css('zIndex') > maxZ) maxZ = $(this).css('zIndex');
})
console.log(maxZ);

jsFiddle example

I think one of the issues with the code you posted is that you're only checking for absolutely positioned elements.

like image 30
j08691 Avatar answered Sep 22 '22 16:09

j08691