|
||||||||
|
|||||||
|
|
Last updated: 25 Mar 2006
Absolutely-positioned DIVs ordering
If your web page can contain several overlapping absolutely-positioned HTML DIV
tags, you might need to bring one forward or send one back.
The javascript offered here does exactly that. Especially useful if you have web page dynamic menus using such DIVs. The navigation will not be obscured anymore.
The effect is achived by changing the z-index style property of HTML DIV elements. Initial
z-index values are not neccessary.
Script demonstration
Script source code
To use the script perform the following steps:
<script type="text/javascript"><!--
/* Script by: www.jtricks.com
* Version: 20060325
* Latest version:
* www.jtricks.com/javascript/blocks/ordering.html
*/
function getAbsoluteDivs()
{
var arr = new Array();
var all_divs = document.body.getElementsByTagName("DIV");
var j = 0;
for (i = 0; i < all_divs.length; i++)
if (all_divs.item(i).style.position=='absolute')
{
arr[j] = all_divs.item(i);
j++;
}
return arr;
}
function bringToFront(id)
{
if (!document.getElementById ||
!document.getElementsByTagName)
return;
var obj = document.getElementById(id);
var divs = getAbsoluteDivs();
var max_index = 0;
var cur_index;
// Compute the maximal z-index of
// other absolute-positioned divs
for (i = 0; i < divs.length; i++)
{
var item = divs[i];
if (item == obj ||
item.style.zIndex == '')
continue;
cur_index = parseInt(item.style.zIndex);
if (max_index < cur_index)
{
max_index = cur_index;
}
}
obj.style.zIndex = max_index + 1;
}
function sendToBack(id)
{
if (!document.getElementById ||
!document.getElementsByTagName)
return;
var obj = document.getElementById(id);
var divs = getAbsoluteDivs();
var min_index = 999999;
var cur_index;
if (divs.length < 2)
return;
// Compute the minimal z-index of
// other absolute-positioned divs
for (i = 0; i < divs.length; i++)
{
var item = divs[i];
if (item == obj)
continue;
if (item.style.zIndex == '')
{
min_index = 0;
break;
}
cur_index = parseInt(item.style.zIndex);
if (min_index > cur_index)
{
min_index = cur_index;
}
}
if (min_index > parseInt(obj.style.zIndex))
{
return;
}
obj.style.zIndex = 1;
if (min_index > 1)
return;
var add = min_index == 0 ? 2 : 1;
for (i = 0; i < divs.length; i++)
{
var item = divs[i];
if (item == obj)
continue;
item.style.zIndex += add;
}
}
//--></script>
Browser compatibility
The javascript snippet above was tested on the following user agents:
Script Rating
| |||||||||||||||||||||||||||||||||||||||||||
| |||||||