How can I change an image when the mouse moves over it?

Some sites have images on their pages that change when you move the mouse pointer over it. How do you create such an effect? First a warning, this technique only works in Netscape Navigator 3.0 and up. Internet Explorer doesn't support it in 3.0, but 4.0 does.

Changing an image only works if the image is inside a link, (the A element). Normally when you use an image in a link the source looks something like this:

Source
<A href="index.html">
<IMG src="home.gif" border="0">
</A>

Result

To identify which of the images on a page must change you must give the image a name, so it can be referred to later on:

Source
<A href="index.html">
<IMG src="home.gif" border="0" name="imgHome">
</A>

Result

Now add the JavaScript that actually changes the images when needed. In the HEAD of the page put this script:

Source
<SCRIPT language="javascript1.1">
gifHome = new Image(54,18)
gifHome.src = "home.gif"
gifHome2 = new Image(54,18)
gifHome2.src = "home2.gif"

function changeImg(cImg,ref) {
document.images[cImg].src = ref.src
}
</SCRIPT>

Then add an onMouseOver event handler to the link. This is a JavaScript statement that gets executed when the user moves the mouse over it:

Source
<A href="index.html" onMouseOver="changeImg('imgHome',gifHome2)">
<IMG src="home.gif" border="0" name="imgHome">
</A>

Result

This works ok, but now the image doesn't change back when the mouse pointer is no longer over the image. To correct this you also have to add an onmouseout event handler to the link:

Source
<A href="index.html" onMouseOver="changeImg('imgHome',gifHome2)"
onMouseOut="changeImg('imgHome',gifHome)">
<IMG src="home.gif" border="0" name="imgHome">
</A>

Result


How can you use this technique?

Follow these steps:
  1. Give every image that you want to be able to change a unique name.
  2. Preload the images. This means that you must create an object for every image you want to be able to load automatically. Add these two lines to the script, but substitute objectName and image.gif to the ones you need.

    objectName = new Image(width,height)
    objectName.src = "image.gif"

    The first line creates a new image object, the second loads the image in memory.

  3. Add onMouseOver and onMouseOut event handlers to the corresponding link.

    Function: changeImg(<image-name>,<object-name>)
    Parameters:
    <image-name>
    The name of the image that must be changed.
    <object-name>
    The object in which the new image is preloaded.

Back to the FAQ main page
Statistics

  Copyright © 1996 - 2000 Rob Schlüter,   schluter@knoware.nl   (last updated 1999/03/01)