Changing the Z-Index

Contact Us or call 1-877-932-8228
Changing the Z-Index

Changing the Z-Index

The z-index value of an element indicates its relative position in the "stack" of elements the page. Elements with higher z-index values sit on top of elements with lower values. You can think of a stack of papers thrown on a table. The ones at the top have a higher z-index than the ones on the bottom. In the screenshot below, the box on the bottom has a higher z-index that the box on top:

The z-index of an object can be changed by modifying the zIndex property of the element's style property. The following example demonstrates this:

Code Sample:

DynamicHtml/Demos/Zindex.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>zIndex</title>
<link href="zindex.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="../../lib.js"></script>
<script type="text/javascript">
	var z = 0;
	function changeZ(elem){
		z += 10;
		elem.style.zIndex = z;
		elem.innerHTML = "z: " + z;
	}

	observeEvent(window,"load",function() {
		var divRed = document.getElementById("divRed");
		var divBlue = document.getElementById("divBlue");
		observeEvent(divRed,"click",function() {
			changeZ(divRed);
		});
		observeEvent(divBlue,"click",function() {
			changeZ(divBlue);
		});
	});
</script>
</head>
<body>
	<div id="divRed"></div>
	<div id="divBlue"></div>
</body>
</html>

The variable z always holds the highest z-index. The function changeZ() simply adds 10 to z and assigns the resulting value to the zIndex property of the passed in object.

Next