Image rollovers

This program shows how to switch an image when the cursor is moved over it, and to switch it back when the cursor is moved away.

Programming Issues

Rather than using the onclick event as in previous examples, we use two new events in this one. The onmouseover event is triggered when the cursor moves over the page element (in this case, the image), and the onmouseout event is triggered when the cursor moves away from that page element. In this example, we call the function changeImage() when both events are triggered, but we pass an argument to it depending on which event was triggered: we call changeImage(0) when onmouseover is triggered, and changeImage(1) when onmouseout is triggered. The function just reads the value of the argument, and if it is 0, it changes to the image of Mars; if it is 1, it changes back to the image of Earth.

Try moving the mouse pointer over and away from the image below to see this in action.

Note: for simplicity, this example does not use image pre-caching.

Demonstration

Earth

Source and Downloads