O'Reilly logo

JavaScript & DHTML Cookbook by Danny Goodman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Swapping Images (Rollovers)

NN 4, IE 4

Problem

You want the picture displayed by an img or image-type input element to change when the user rolls the mouse over the element.

Solution

There are two parts to the solution. The first part is a generic and backward-compatible image swapping function, called setImage( ) , that can be used by any number of images on the page. The following function assumes the existence of a custom object referencing precached images, as shown in Recipe 12.1:

function setImage(imgName, type) {
    if (document.images) {
        if (type =  = "hilite") {
            document.images[imgName].src = imagesHilite[imgName].src;
            return true;
        } else if (type =  = "normal") {
            document.images[imgName].src = imagesNormal[imgName].src;
            return true;
        }
    }
    return false;
}

Because the earliest browsers supporting swappable images did not support mouse events for img elements, the images had to be surrounded by a elements, which did respond to mouse events:

<a href="products.html" onmouseover="return setImage('products', 'hilite')"
    onmouseout="return setImage('products', 'normal')"><img name="products" 
    height="20" width="50" border="0" src="img/prodNormal.jpg" alt="Products"></a>

For IE 4 or later and NN 6 or later, you can skip the a element, and trigger the rollover directly from the img element's mouse events, provided you also program navigation you wish to associate with a click on the image:

<img name="products" height="20" width="50" src="img/prodNormal.jpg" alt="Products" onmouseover="return ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required