How can I create images which change when the mouse passes over them?
Do you mean something like this? (Move your mouse cursor over the arrow buttons but please do not click on them.)To produce the effect shown in the example above, you must be able to do two things:
onMouseOver
and onMouseOut
events for the image. The following code shows many people's first attempts at this task:
Unfortunately, this doesn't work because image objects do not support
onMouseOver
and onMouseOut
events.
Fortunately, this deficiency is easy to work around. Another kind of object, the hyperlink object, does support the onMouseOver
and onMouseOut
events. Thus, in order to detect whether the cursor is over an image, we can simply turn the image into a hyperlink and process the hyperlink's mouse events, as shown in the following example:
Now that we know how to program mouse event handlers for images, let's move on to the next step: changing the image.
src
which contains the URL of the image being displayed. To change the image, simply assign a new image URL to the image object's src
property.
The document
object contains an array property called images
which can be used to access every image in the document. You can index the array either by an integer or by the image's name (if it has one). For example, suppose we used the following HTML document to display images of three fruits:
After the document has loaded, we can use either of the following two JavaScript statements to change the orange into an apple:
document . images [2] . src = "apple.gif";
document . images ["orange"] . src = "apple.gif";
document . images
array because the orange image is the third image in the document (remember, array indices begin with 0, not 1).
The second approach uses the image's name, "orange", as an index into the document . images
array. This is a better solution because image names do not change when new images are inserted at the beginning of the document, but numerical indices do.
The normal and "pushed" images, along with their filenames, are shown below:
The following HTML/JavaScript code uses the techniques discussed in this article to implement the scenario described above. Study this code carefully!
left right normal
ol.gif
or.gifpushed
il.gif
ir.gif(The letters o, i, l, and r indicate out, in, left, and right, respectively.)
There are at least two ways to eliminate this delay through image pre-caching, but I will not discuss them here because they go beyond the scope of this tutorial. (If I get enough requests for it, I will produce another tutorial to demonstrate these techniques.)
Charlton Rose
31 Dec. 1996