Images

The images[] property of the Document object is an array of Image elements, each representing one of the inline images, created with an <img> tag, that is contained in the document. The images[] array and the Image object were added in JavaScript 1.1. While web browsers have always been able to display images with the <img> tag, the addition of the Image object was a major step forward -- it allowed programs to dynamically manipulate those images.

Image Replacement with the src Property

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. For this to work, the new image must have the same width and height as the original one.

In practice, the most common use for image replacement is to implement image rollovers, in which an image changes when the mouse pointer moves over it. When you make images clickable by placing them inside your hyperlinks, rollover effects are a powerful way to invite the user to click on the image. Here is a simple HTML fragment that displays an image within an <a> tag and uses JavaScript code in the onmouseover and onmouseout event handlers to create a rollover effect:

<a href="help.html" onmouseover="document.helpimage.src='images/help_rollover.gif';" onmouseout="document.helpimage.src='images/help.gif';"> <img name="helpimage" ...

Get JavaScript: The Definitive Guide, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.