HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Finding max z-index featuring in the current page

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
themaxfeaturingpagecurrentfindingindex

Problem

I have to display a cache layer on the whole viewport (to then display a kind of dialog box).

Without surprise I create a ` element with {position: fixed; top: 0 left: 0; width: 100%; height: 100%: background-color: #...; opacity: ...}.

But I faced the issue that I may encounter pages where some elements have a
z-index other than 0 or auto.

So I must add a
z-index property which surpasses the maximum one currently featuring in the page.

I'm currently using the following snippet:

var zMax = 0;
$('body *').each(function() {
  var zIndex = +$(this).css('zIndex'); // ("+" casts to number or NaN)
  if (zIndex > zMax) {
    zMax = zIndex;
  }
});


It works fine, but I'm not really happy with it: merely based on brute-force, it appears as "too easy" and a bit overkill.

I googled for other solutions and found a lot (notably on SO), but no one seems simpler than mine.

TL;DR; Is there some smarter alternative?

EDIT: to be more clear, here is an example of how the "cache layer" works:



$(document).ready(function() {
$('#go, #goz').click(showDialog);

});
function showDialog() {
$('body').append('');
$('body').append('Cancel');
$('#cancel').click(cancel);
var text = 'Without z-index, cache doesn\'t cover image';
if (this.id == 'goz') {
$('#cache').css({zIndex: 101});
$('#dialog').css({zIndex: 102});
text = 'With z-index, cache covers all';
}
$('#text').html(text);
}
function cancel() {
$('#dialog, #cache').remove();
}
#cache {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #444;
opacity: .7;
}
img {
position: relative;
z-index: 100;
}
#dialog {
position: fixed;
left: 100px;
top: 50px;
width: auto;
border: 1px solid #000;
background-color: #fff;
padding: 1em;
}


Longe glabro ortus tempus crimina perquam notarius Magnentio odorandi in membra quos a perquam supergressus.

Batnae municipium in Anthemusia conditum Macedonum manu priscorum ab Euphrate

Solution

While I understand you're looking for a snippet that works well on an underlying page you have no control over, any solution for such a problem would technically be a hack.

Your best bet, though certainly not a fool-proof solution, is to just use a very large or perhaps the maximum possible z-index (supposedly 2147483647, though certainly not standardised - I'd just go with something like 10000000) on your element.

Context

StackExchange Code Review Q#143336, answer score: 2

Revisions (0)

No revisions yet.