In a forum that I frequent, someone asked how they could replace their arbitrary z-index values to only the range needed to get the job done. For example, if they had only 3 z-index values being used (”0″, “30″, “500″) they wanted this to replace them to the smallest values possible (”0″, “1″, “2″). Is this useful? Probably not. But here is my 20 minute solution:
<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>
<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>
0 Responses
Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.