In particular, Nathan Wrigley of pictureandword.com, needed a method one image into another mouse rolls over, and the slowly fade back once the mouse has left.

Image rollovers were the staple JavaScript nugget of the 90s, and for a lot of JavaScript developers I know, one of the starting places their passion for JavaScript. Today, rollovers are a no-brainer – either in CSS or with the simplest of JavaScript:

How to Approach the Problem

There are a few different ways which problem can be solved (and I’d love to hear alternative methods via the comments).

Here are the ways I’m going to go through:

Two Image

Single Image

Pure CSS

The key to all of these techniques is how the rendered markup (i.e. what the browser finally sees) is arranged: all of which are very similar.

Essentially, the end image for the transition must sit absolutely in the same position as the starting image.

It’s also worth keeping in mind that the images we fade between should be the same size (height & width-wise).

Note: all three of these techniques have a caveat: styling the start or end image may cause the effect to break. I would recommend wrapping the image in a div or span and styling that element, as it will require less changes to the JavaScript. Either way: it is always best to test in the target browsers.

Two Image Technique

Karl’s method starts with the two images in the markup: both the start and end images. They are contained in a div and the end image is contained in a further div with absolute positioning.

It is important to note that this technique works best for absolutely position images. Changing the div.fade to position: relative means the div element remains as a block element, and div will stretch the with of it’s container element (defaulting to 100%).

Single Image Technique

This takes the two image technique further. I like the idea that we should let the JavaScript add the sugar to the markup – in that we should really only want an image tag, and using some method to know what image we want to fade to.

This technique allows us to insert the image in the markup as we would if there were no transition effect, and the image can be inline, rather being positioned absolutely.

We are going to use the background-image CSS property to specify the target image to fade to.

HTML

CSS

Although this is only supported in Safari 3, the roll over still works in Firefox (and could work in IE7 – though not IE6 because :hover only works on anchors) – because it’s changing the image’s opacity on :hover.