Generic JavaScript Swap Image

This page demonstrates how to change an img from an event (e.g. onclick, onmouseover, etc) of any element (e.g. img, span, etc).

This work is licensed under a Creative Commons License.

Syntax

preload(array);
swapImg(event, newImg[, imgId]);

Arguments

array
An array of strings that specify the URLs of the images to preload.
event
The standard event object
newImg
The image to use. This can be an URL or an index into the array of preloaded images.
imgId
Optional. The id of the img element to change. If omitted, the event source element is changed.

Remarks

If newImg is a number, the function preload must have been called and newImg must be a valid index, e.g. 0 <= newImg < array.length.

If the imgId argument is omitted, the element the event is attached to must be a img element.

Examples

Prerequisites

Include imgswap.js. If you want to preload the images you plan to swap, add a script block after the include one and call the function preload. The result might look like this:

<script type="text/javascript" src="imgswap.js"></script>
<-- Only needed when preloading images -->
<script type="text/javascript">
preload(["img3.png", "imgs/img4.png"]);
</script>

Compatibility

This code has been tested in: Internet Explorer (IE) 5.01, IE5.5, IE6, IE5.2/Mac, Mozilla Firebird 0.7, Opera 7.23 and Safari.

Version history

2004-01-16

Download

imgswap.js