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.
preload(array); swapImg(event, newImg[, imgId]);
arrayeventevent objectnewImgimgIdid of the img element
to change. If omitted, the event source element is changed.
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.
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>
span element
to change the img with the id "foo":
the <span onclick="swapImg(event, 'img2.png', 'foo');">span</span> <img id="img1" src="img1.png" />
img
element to change the img with the id "img2"
to the second image in the preload array:
<img onmouseover="swapImg(event, 1, 'img2')" src="img1.png" /> <img id="img2" src="img2.png" />
img
element itself:
<img onmouseout="swapImg(event, 'img2.png')" src="img1.png" />
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.