Forum Moderators: open
I have a script which dynamically generates divs whose Z-indexes are changed every time one div is clicked on (brought to focus). Now, because of this, there could be huge and tiny z-indexes at the same time. For instance, element A might have a z-index of 563 while B has one of 30 and C has one of 2. How would one go about writing a function that would reassign every element in the document so that its z-index was only as high as it needed to be? (e.g. rather than 563, 30, 2, it would be, 3, 2, 1). Thanks in advance.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
<!-- Styles -->
<title>Replace Arbitrary z-index values with ordered values</title>
</head>
<body>
<div style="z-index:563">A</div>
<div>A.1</div>
<div style="z-index:2">B</div>
<div style="z-index:30">C</div>
<div style="z-index:563">D</div>
<!-- Scripts -->
<script type="text/javascript" src="http://yui.yahooapis.com/2.5.2/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script type="text/javascript">
YAHOO.util.Event.onDOMReady(function () {
var i, z, a = [];
var zIndexMap = {};
// Get all of the elements that you want to check for z indexes. Use
// whatever makes sense. For this demo, I'm just getting all div elements
var els = document.getElementsByTagName('div');
// Loop through the elements to get the z-indexes
for (i = 0; i < els.length; i++) {
z = YAHOO.util.Dom.getStyle(els[i], 'z-index');
// Check the hash map to see if this is a unique z-index, ie - one that
// we haven't recorded yet.
if (zIndexMap['z' + z] === undefined) {
// We found a unique zindex so add it to our array and mark it found
a[a.length] = parseInt(z, 10);
zIndexMap['z' + z] = 1;
}
}
// Sort our array numerically
// Before sort:
alert('Our unique z-indexes, unsorted:\n' + a);
function numberorder(a, b) { return a - b; }
a.sort(numberorder);
// after sort:
alert('Our unique z-indexes, sorted:\n' + a);
// Loop through the array and record the index value (i) as the new value
// that the hash map points to for this old z-index. For example, if the
// first item in the array contains "563", then our zIndexMap["z563"] = 0.
for (i = 0; i < a.length; i++) {
zIndexMap['z' + a[i]] = i;
}
// Loop through the element collection again and change the z-index value
// by using the old value to lookup the new value in the hash map
for (i = 0; i < els.length; i++) {
z = YAHOO.util.Dom.getStyle(els[i], 'z-index');
YAHOO.util.Dom.setStyle(els[i], 'z-index', zIndexMap['z' + z]);
}
// Verify the new z-index values
for (i = 0; i < els.length; i++) {
alert(YAHOO.util.Dom.getStyle(els[i], 'z-index'));
}
});
</script>
</body>
</html>
[edited by: Fotiman at 9:25 pm (utc) on June 6, 2008]