The Internet Classroom
Javascript Example: Image Rollovers for multiple images
2006/07/22 15:27:16 PDT by kass
Edited at 2006/07/23 12:25:39 PDT
[kass's avatar]

So on the javascript intro day, I demo-ed a couple of examples, one of them being an images rollover example. The code written for that particular example only handles one image at a time and, while it can be easily expanded to handle more than that, I thought I'd try to find a cleaner way to do it. So here it is.

<script type="text/javascript">

function handleOver(imgName) { 
	imgOn = new Image();
	imgOn.src = imgName + "_on.gif";
	document.getElementById(imgName).src = imgOn.src;
}

function handleOut(imgName) {
	imgOff = new Image();
	imgOff.src = imgName + "_off.gif";
	document.getElementById(imgName).src = imgOff.src;
}

</script>

Then in your HTML...

<a href="gosomewhere.html" onmouseover="javascript:handleOver('image1');"
onmouseout="javascript:handleOut('image1');">
<img src="image1_off.gif" id="image1" alt="" /></a>

<a href="gosomewhere.html" onmouseover="javascript:handleOver('image2');" 
onmouseout="javascript:handleOut('image2');">
<img src="image2_off.gif" id="image2" alt="" /></a>

Things to know...

  • You must have a uniform method for naming your images. (e.g. all the "on" images are named "imagename_on.gif", "image2name_on.gif" and same with the "off" images.)

  • Change the javascript apporpriately if you are using something other than _on.gif/_off.gif

  • The parameter that you pass in when you call the function (javascript:handleOver('_PARAMETER_'); is the base name of the image that you want to be changing for that link. So if your images are "cat_on.jpg" and "cat_off.jpg" ... the base name is "cat", so you should be calling handleOut like so -- javascript:handleOut('cat');

  • Need to have a unique ID on the image itself that matches the base name of the image

All TIC materials copyright © 2006 Cynthia Nie and Trevor Ridinger
Powered by Io Community Manager, Evlan, and FreeBSD