« Part 5 | Part 7 »

Part 6 - How to manipulate the depth/order of widgets on the screen (zIndex)

The zIndex CSS attribute controls the stacking order of objects on the screen (like a stack of cards, the lower the zIndex, the further the widget is on the bottom of the stack).

Check out this example of zIndex shuffling

Here’s the Javascript code:


var firefox=document.getElementById&&!document.all;
document.onmousedown=changeZ;
var z=10;
function changeZ(e) 
{	
	if (firefox){
		if (e.target.nodeName=="DIV" && e.target.attributes['id'].value=="redbox"){	
			document.getElementById("redbox").style.zIndex=z;
			z++;
		}
		else if (e.target.nodeName=="DIV" && e.target.attributes['id'].value=="bluebox"){	
			document.getElementById("bluebox").style.zIndex=z;
			z++;
		}
	}
	else{		//IE
		if (event.srcElement.nodeName=="DIV" && event.srcElement.attributes['id'].value=="redbox"){	
			document.getElementById("redbox").style.zIndex=z;
			z++;
		}
		else if (event.srcElement.nodeName=="DIV" && event.srcElement.attributes['id'].value=="bluebox"){	
			document.getElementById("bluebox").style.zIndex=z;
			z++;
		}
	}
}

Whenever the mouse is clicked the browser calls the changeZ function. Within the function, we first verify which browser the user is using and then check if the user has clicked one of the boxes. If we find out that one of the boxes was clicked, we set its zIndex CSS attribute to z, our zIndex counter, thus forcing the browser to redraw the box on top the other box. Don’t forget to increment the counter.