Dynamic Rollover Images in JavaScript


About dynamic images in JavaScript

Working with the images array

Images can be changed dynamically using the images array. All images in an HTML document are accessible from this array. These array elements are numbered as document.images[?] subscripts from 0 upwards. The first subscript being the first image appearing in the HTML document.

Images array properties

The images array has no methods

Images array event handlers

Pre-Loading of images

Images can be pre-loaded into the images array as shown below.

image1 = new Image ();
image1.src = "arrow1.gif";
image2 = new Image ();
image2.src = "arrow2.gif";

Rollovers

Rollovers are usually used for images that are linked. When the mouse is moved over an image the image changes. Move the mouse over the blue arrow below and watch it turn red whilst the mouse moves over the image. Rollovers are useful for menu options where the selected option's image changes and thus that selected option is highlighted.

Arrows

The code for the rollover looks as below.

A HREF=""
	onMouseOver="document.images[1].src='../graphics/redArrow.gif'"
	onMouseOut="document.images[1].src='../graphics/blueArrow.gif'"
	IMG SRC="../graphics/blueArrow.gif"
	BORDER="0"
/A

A simple animation using JavaScript

This can be done one of two ways. The images can be pre-loaded and then cycled through or the images can be loaded one at a time as required. The code below is the cycle() function which loads each image as required. Note that each image is only downloaded from the server once. The once download means the image is in RAM whilst the page is active. Since the page images are in RAM (not just downloaded onto your machine's hard-drive) the access time is negligible when compared to the download time. Note that this method of animation is less efficient than an animated GIF file.

var i;
i = 1;
function cycle()
{
	if (document) 
	{
		if (document.images)
		{
			document.images[1].src = "../graphics/banner" + [i] + ".gif";
			++i;
			if (i > 6)
			{
				i = 1;
			}
			window.setTimeout ("cycle();", 3 * 1000)
		}
	}
}