Aug 24 2009

Rollover Images – CSS versus JavaScript

I seem to always wrestle with this no matter how many times it comes up. When a website design calls for image-based rollovers on the primary navigation, rollover which method to use? CSS or JavaScript. Accessibility for me in this context is that the navigation must be functional if one or any combination of the following is disabled: JavaScript, CSS, images. It also validate as XHTML Strict, CSS level 2WCAG priority 2, and it (obviously) must work with screen readers. Browser compatibility doesn’t factor in heavily here, but it must work in my standard browser list, which includes IE6. I also consider the actual rollover effect itself to be non-essential.

CSS Benefits

  • [Maintenance] Can use one “sprite” based image for all items (changing background position to show the different items)
  • [Accessibility] Works even if JavaScript is disabled
  • [Accessibility] Shows text if images are disabled (via Ryan Rollovers method)

CSS Cons

  • [Maintenance] Funky HTML/CSS needed for full accessibility (the empty span trick of Ryan Rollovers)
  • [Extras] Will probably look bad if printed (since background images don’t print by default)

JS Pros

  • [Accessibility] Can use forground images with alternate text
  • [Maintenance] Simple, clean inline script using “onmouseover” and “onmouseout”
  • [Accessibility] Shows alt text if images are disabled
  • [Extras] Will print foreground images by default so printout should look better

JS Cons

  • [Maintenance] Will have many images to deal with – 2 for each item. If one image changes width, you need to redo all images and rollover states.

Both methods have a potential issue of when images are disabled, then the foreground or alternate text spacing can be tricky. Result can be that even though the text is displayed, it will be difficult to read.

I think that looking at these items summed up shows the direction I should take. As far as I can tell, the simple JavaScript method provides the most benefits with the least amount of potential problems. So it shall be!