Skip to content

Instantly share code, notes, and snippets.

@karbassi
Created December 10, 2009 01:57
Show Gist options
  • Save karbassi/253042 to your computer and use it in GitHub Desktop.
Save karbassi/253042 to your computer and use it in GitHub Desktop.
The following Javascript finds the highest z-index in the page and changes the
background color to orange.
What I'm trying to do is find the DOM element with the highest z-index. I have
the following code, but I can't figure out how to do it without having the variable "high".
Can you figure out a better way?
Also, it doesn't seem to work in Safari.
jQuery(document).ready(function($) {
var high = 0,
max = $.map($('body > *'), function(e, n) {
n = parseInt($(e).css('z-index'), 10) || 1;
if( n > high ) {
high = n;
return $(e);
}
}).pop();
$(max).css('background-color', 'orange');
});
<!DOCTYPE html>
<html>
<head>
<title>Highlight element with the highest z-index</title>
<style type="text/css" media="screen">
#z1 {z-index:1;}
#z2 {z-index:2;}
#z3 {z-index:3;}
#z4 {z-index:4;}
#z5 {z-index:5;}
#z6 {z-index:6;}
#z7 {z-index:7;}
#z8 {z-index:8;}
#z9 {z-index:9;}
#z10 {z-index:10;}
#z11 {z-index:11;}
#z12 {z-index:12;}
#z13 {z-index:13;}
div{width:100px;height:100px;border:1px solid orange;float:left;margin:10px;font-size: 5em;text-align: center;line-height: 1.4em;}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
<script src="find_highest_z.js" type="text/javascript"></script>
</head>
<body>
<div id="z8">8</div>
<div id="z10">10</div>
<div id="z3">3</div>
<div id="z1">1</div>
<div id="z7">7</div>
<div id="z4">4</div>
<div id="z12">12</div>
<div id="z13">13</div>
<div id="z6">6</div>
<div id="z9">9</div>
<div id="z11">11</div>
<div id="z2">2</div>
<div id="z5">5</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment