Find top z-index
In Category Useful FunctionsArticle published 12/01/2010 04:41:00pm

If you want to dynamically move an element on a webpage to the "top" position, this function lets you find the current top z-index on the fly. Extremely important if you need to overlay content on a page with changing content!
This function allows you to quickly find the topmost current z-index of all elements on a page. The returned value is equal to the topmost z-index, so if you wish to overlay all page content you should add one (+1) to the returned number.
Note: Some elements, such as select boxes, will always appear topmost on a page, overlaying other content. This is a known browser issue that as of yet has not been resolved.
The function follows these steps:
- Fetch a list of page elements using either getElementsByTagName or document.all depending on the browser
- Looping through all page elements and checking if they have a z-index
- If a z-index value is found that is higher than the current highest, the current highest is changed to reflect it
- The highest found z-index is returned by the function
The code is as follows (Javascript):
function find_topmost() {
current_top = 0;
if(document.getElementsByTagName) {
page_elements = document.body.getElementsByTagName('*');
} else if(document.all) {
page_elements = document.all;
} else { return false; }
for(i=0;i<page_elements.length;i++) {
if(page_elements[i].style.zIndex &&
parseInt(page_elements[i].style.zIndex)>current_top) {
current_top = parseInt(page_elements[i].style.zIndex);
}
}
return current_top;
}
current_top = 0;
if(document.getElementsByTagName) {
page_elements = document.body.getElementsByTagName('*');
} else if(document.all) {
page_elements = document.all;
} else { return false; }
for(i=0;i<page_elements.length;i++) {
if(page_elements[i].style.zIndex &&
parseInt(page_elements[i].style.zIndex)>current_top) {
current_top = parseInt(page_elements[i].style.zIndex);
}
}
return current_top;
}