Dan's Layers Tutorial
2.5  Changing Images

If you need to switch images during an animation, you first have to preload that image. The general code for preloading images is:

imagename = new Image();
imagename.src = "filename.gif";

If the image you want to switch is an animated GIF you have to include the height and width of the image (in pixels) :

imagename = new Image(height,width);
imagename.src = "filename.gif";

The command to switch an image will go something link this:

document.layers["layername"].document.images[index].src = imagename.src

Where "index" is the number of the image you want to change. The first image in your layer has an index of 0, the second has an index of 1 and so on.

To show how this works I've created an example that uses this script:

imageB = new Image();
imageB.src = "imageB.gif";

function movelayer() {
	if (document.layers["layer1"].left < 250) {
		document.layers["layer1"].left += 5;
	else {
		document.layers["layer1"].document.images[0].src = imageB.src

In the layer tag we only need to define "imageA.gif" because we will dynamically replace that image with "imageB.gif" after it's done the slide. You could accomplish the same task by defining 2 separate layers and then hiding and showing them, but switching the images is often easier.

<LAYER NAME="layer1" LEFT=50 TOP=50>
<IMG SRC="imageA.gif" WIDTH=75 HEIGHT=75 BORDER=0>

Here are the images I'll be using:



Dan's Layers Tutorial
1.1 Introduction
1.2 Overlapping
1.3 Nesting
1.4 Using JavaScript
2.1 Sliding Layers
2.2 Pre-Built Functions
2.3 Clipping Layers
2.4 Looping Animations
2.5 Changing Images
3.1 Mouse-Click Animation
3.2 Capturing Keystrokes
3.3 Drag and Drop
4.1 Making Demos
4.4 Problems
4.5 Screen Sizes

Copyright © 1997 Dan Steinman. All rights reserved.