CSS / JavaScript: Make the element the largest z-index / most modal element

I would like to make an element (like a <div> ) the topmost layer on the page.

My assumption is that the only way to do this is to indicate that the element has a style="z-index:" value, which is the maximum allowed for the browser (int32?).

Is it correct?

Instead, is it possible to somehow get the z-index element that is the highest and make it <div> z-index [highest element value] + 1 ? For example:

 $myDiv.css("z-index", $(document.body).highestZIndex() + 1); 

How do modal JavaScript windows work?

+6
javascript html css modal-dialog z-index
source share
4 answers

Here's how to do it:

 var elements = document.getElementsByTagName("*"); var highest_index = 0; for (var i = 0; i < elements.length - 1; i++) { if (parseInt(elements[i].style.zIndex) > highest_index) { highest_index = parseInt(elements[i].style.zIndex; } } 

high_index now contains the highest z-index on the page ... just add 1 to this value and apply it wherever you want. You can apply it like this:

 your_element.style.zIndex = highest_index + 1; 

Here is another way to achieve the same using jQuery:

 var highest_index = 0; $("[z-index]").each(function() { if ($(this).attr("z-index") > highest_index) { highest_index = $(this).attr("z-index"); } }); 

Again, the same as applying a new index to an element:

 $("your_element").attr("z-index", highest_index + 1); 
+8
source share

What about the stacking context? It is not always true that: In the document, the superscript z will be on top. See: http://philipwalton.com/articles/what-no-one-told-you-about-z-index/ . If you don't take into account the stacking context, setting a billion might not be enough to make your item the topmost.

+2
source share
+1
source share

Syavi jQuery solution does not work because z-index is a css style, not an attribute.

Try this instead:

 raiseToHighestZindex = function(elem) { var highest_index = 0; $("*").each(function() { var cur_zindex= $(this).css("z-index"); if (cur_zindex > highest_index) { highest_index = cur_zindex; $(elem).css("z-index", cur_zindex + 1); } }); return highest_index; }; 

The return value may not be what you expect due to the nature of asynchronous Javascript, but a function call on any element will work fine.

+1
source share

All Articles