I recently had cause to do battle with IE6 and 7 whilst implementing some updates to various sites. One of the bugs I came up against was IE’s odd z-index implementation.
The site features a list of items which include thumbnail images. When hovering the mouse pointer over the thumbnail, a larger version of the image is displayed – tooltip style. The problem is that the larger version of the image overlaps the preceding and following list item. In IE 6 & 7 the following list item displays on top of the large image, despite it having been given a higher z-index in the CSS file.

Intended Effect

IE Bug
This bug is caused by the fact that the list items have relative positioning (in order to position the elements within each item). IE resets the z-index stack for elements within positioned elements.
In Internet Explorer positioned elements generate a new stacking context, starting with a z-index value of 0. Therefore z-index doesn’t work correctly. quirksmode.org
The way to solve this is to ensure that the positioned parent element (the list item) has a higher z-index than the positioned elements to be overlapped – in this case, the other items in the list.
My solution here was thanks to the fact that the site was using jQuery, I was able to implement a very simple piece of code to dynamically alter the z-index values of the items in the list.
$('#list a.thumb').mouseover(function(){
$(this).parent('li').css('z-index', 2).siblings('li').css('z-index',1);
});
I’ll break this down as jQuery’s function chaining enables very tight but occasionally difficult-to-read code.
Firstly I bind a function to the mouseover event of the thumbnail image
$('#list a.thumb').mouseover(function(){
...
});
next comes the clever bit, jQuery includes a powerful set of DOM traveresal methods which allow you to dance around the document like a scripty Rudolph Nureyev without the need for messy classes and id’s on every other element.
$(this) //selects the anchor tag over which the mouse has moved
.parent('li') //traverse to the anchor's parent li element
.css('z-index', 2) //set the z-index to 2 on the li
.siblings('li') // selects the sibling li elements (not including the one we just changed)
.css('z-index',1); //sets the z-index to 1 on all of the sibling li elements
By inserting the code into a $(document).ready function the behaviour is applied as soon as the page has loaded.
Tweet This
Digg This








how to fix the IE z-index bug with jQuery | Web Developer 2.0 http://bit.ly/8M9vXQ #jQuery
This comment was originally posted on Twitter
How to fix the IE z-index bug with jQuery | http://bit.ly/8M9vXQ | #tech
This comment was originally posted on Twitter