Sams Teach Yourself JavaScript in 24 Hours

Sams Teach Yourself JavaScript in 24 Hours

By Michael Moncur

Using Dynamic Images in JavaScript

One of the most useful features of JavaScript is the capability to dynamically change images. This means you can create images that "magically" change, which could be used for clocks, image rollovers (images that change when you move the mouse over them), or even simple animations.

The images in a Web page are reflected in an array, just like form elements. By modifying the properties of the array items, you can replace the image with a different one. This enables you to create dynamically changing content on the page without even using frames or layers.

This technique isn't perfect for all applications. Before you get started, note the following limitations:

Working with the images Array

You can change images dynamically by using the images array. This array contains an item for each of the images defined on the page. Each image can also have a name. In the object hierarchy, each image object is a child of the document object.

Each image object has the following properties:

For most purposes, the src attribute is the only one you'll use. However, you can also change the lowsrc attribute. This defines a low-resolution image to load first and will be used only when you change the src attribute.

The image object has no methods. It does have three event handlers you can use:

Preloading Images

Although you can't add an image to the page dynamically, you can create an independent image object. This enables you to specify an image that will be loaded and placed in the cache, but will not be displayed on the page.

This may sound useless, but it's a great way to work with modem-speed connections. Once you've preloaded an image, you can replace any of the images on the page with that image—and because it's already cached, the change happens instantly.

You can cache an image by creating a new image object, using the new keyword. Here's an example:

Image2 = new Image();
Image2.src = "arrow1.gif";

Share ThisShare This

Informit Network