Skip to content

Instantly share code, notes, and snippets.

@oakmac
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oakmac/14304a37eefc1618100f to your computer and use it in GitHub Desktop.
Save oakmac/14304a37eefc1618100f to your computer and use it in GitHub Desktop.
Example of Layering Technique for z-indexed menus
<!doctype html>
<html lang="en-us">
<head>
<meta charset="utf-8" />
<meta content="IE=edge" http-equiv="X-UA-Compatible" />
<title>z-index Layering Example</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
font-family: Helvetica, sans-serif;
padding: 40px;
}
button {
display: block;
padding: 5px 10px;
}
h1 {
margin-bottom: 20px
}
.menu {
background: #f5f5f5;
border: 1px solid #ddd;
min-width: 180px;
padding: 20px;
position: absolute;
z-index: 100;
}
.menu ul {
margin: 20px;
}
.menu li {
padding: 4px 0;
}
p {
padding: 10px 0;
}
#menuLayer {
height: 100%;
left: 0;
opacity: 1;
position: fixed;
top: 0;
width: 100%;
z-index: 99;
}
</style>
</head>
<body>
<h1>Layering Example</h1>
<button id="button1">Toggle Menu</button>
<div id="menuContainer">
<div class="menu" id="theMenu" style="display:none">
<h4>Options</h4>
<ul>
<li>Option 1</li>
<li>Option 2</li>
<li>Option 3</li>
<li>Option 4</li>
<li>Option 5</li>
</ul>
</div><!-- end .menu -->
</div>
<p>Some text will be here; the menu will be on top of this text.</p>
<p>Some text will be here; the menu will be on top of this text.</p>
<p>Some text will be here; the menu will be on top of this text.</p>
<p>Some text will be here; the menu will be on top of this text.</p>
<p>Some text will be here; the menu will be on top of this text.</p>
<p>Some text will be here; the menu will be on top of this text.</p>
<p>Some text will be here; the menu will be on top of this text.</p>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
var menuShowing = false;
function byId(id) {
return document.getElementById(id);
}
function addLayerDiv() {
$('body').append('<div id="menuLayer" style="display:none"></div>');
}
function hideMenu() {
$('#theMenu').hide();
$('#menuLayer').hide();
menuShowing = false;
}
function showMenu() {
if (! byId('menuLayer')) {
addLayerDiv();
}
$('#theMenu').show();
$('#menuLayer').show();
menuShowing = true;
}
function clickBtn1() {
if (menuShowing) {
hideMenu();
}
else {
showMenu();
}
}
function addEvents() {
$('#button1').on('click', clickBtn1);
$('body').on('click', '#menuLayer', hideMenu);
}
function init() {
addEvents();
}
init();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment