22.1.2. Traditional Image Rollovers
The main feature of the Image object is that its src property is read/write. You can read this property to obtain the URL from which an image was loaded, and, more importantly, you can set the src property to make the browser load and display a new image in the same space.
[*] No discussion of image rollovers is complete without pointing out that they can also be implemented using the CSS :hover pseudoclass to apply different CSS background images to elements when the mouse "hovers" over them. Unfortunately, making CSS image rollovers work portably is difficult. In practice, :hover is more useful when applied to hyperlinks containing text, rather than images.
<img name="helpimage" src="images/help.gif" border="0">
Note that in this code fragment, the <img> tag has a name attribute that makes it easy to refer to the corresponding Image object in the event handlers of the <a> tag. The border attribute prevents the browser from displaying a blue hyperlink border around the image. The event handlers of the <a> tag do all the work: they change the image that is displayed simply by setting the src property of the image to the URLs of the desired images. These event handers are placed on the <a> tag for the benefit of very old browsers that support those handlers only on specific tags, such as <a>. In virtually every browser deployed today, you can also put the event handlers on the <img> tag itself, which simplifies the image lookup. The event-handler code can then refer to the Image object with the this keyword:
Image rollovers are strongly associated with clickability, so this <img> tag should still be enclosed in an <a> tag or given an onclick event handler.
22.1.3. Offscreen Images and Caching
In order to be viable, image rollovers and related effects need to be responsive. This means that you need some way to ensure that the necessary images are "prefetched" into the browser's cache. To force an image to be cached, you first create an Image object using the Image( ) constructor. Next, load an image into it by setting the src property of this object to the desired URL. This image is not added to the document, so it does not become visible, but the browser nevertheless loads and caches the image data. Later, when the same URL is used for an onscreen image, it can be quickly loaded from the browser's cache, rather than slowly loaded over the network.
The image-rollover code fragment shown in the previous section did not prefetch the rollover image it used, so the user might notice a delay in the rollover effect the first time she moves the mouse over the image. To fix this problem, modify the code as follows:
<script>(new Image( )).src = "images/help_rollover.gif";</script>