Home

Nate Wienert

Developer, Designer. Creator of 2u.fm, GameGum & obtvse.

Performance Tip: Showing and hiding lots of element in IE7 and IE8

I’ve been working on a new feature for the Zappos product page that involved 45 images. Moving your mouse would show or hide one of the images at a time depending on it’s position. My first instinct was to drop them all into a div, position absolute, and update the z-index to show just one. The HTML and Javascript was something like this (warning: code examples in this post are all pseudo code):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
< div id="imageContainer">
  < img src="..." />
  < img src="..." />
  ...
< /div>

$('#imageContainer').mousemove(function() {
  var index = getIndexFromMousePosition();
  if (active) active.classname = '';
  active = image[index];
  active.classname = 'active';
}

img {z-index:1;}
img.active {z-index:2;}

Unfortunately in IE8 and below this was extremely slow, it would take on the order of a second or so to update the image on my year-old Macbook Pro.

After some googling I didn’t find any good answers to the problem, but with some help and experimentation I found that placing the images into a wrap div, floating them all left, and then updating the wrap div with the corresponding left position fixed it. Something like this:

1
2
3
4
5
6
7
8
9
10
11
12
< div id="imageContainer">
  < div id="imageWrap">
    < img src="..." />
    < img src="..." />
    ...
  < /div>
< /div>

$('#imageContainer').mousemove(function() {
  var index = getIndexFromMousePosition();
  $('#imageWrap').css('left', '-' + (imageWidth * index) + 'px';
}

Done! Just posting this in the hopes that anyone googling for better performance in IE showing and hiding elements with javascript.