clicking on this will visually collapse the text block directly below it

JavaScript Tutorial - Page Three, Image Swapping

Image swapping is a staple of the web. Button rollovers are amongst the most common uses for this but with a little creativity there are a million different uses. There are simple ways to do these swaps but most of those are murdered by our old friend Netscape. So after looking at a couple of different ways to do this and peeking at a few other peoples code I came up with this completely cross-browser usable script.

Loading the Image Array

The most important part of this script is creating the image array. I also like to load the entire path to the image into this array. This is what it looks like:
<script><!--
imageArray = new Array(8);
imageArray[0] = "/images/imageA.jpg";
imageArray[1] = "/images/imageB.jpg";
imageArray[2] = "/images/imageC.jpg";
imageArray[3] = "/images/imageD.jpg";
imageArray[4] = "/images/imageE.jpg";
imageArray[5] = "/images/imageF.jpg";
imageArray[6] = "/images/imageG.jpg";
imageArray[7] = "/images/imageH.jpg";

Then create a function that accepts the image number to do the switching like this:

function changeImage (imgNum) {
    document['mainImage'].src = imageArray[imgNum];
    }
//-->
</script>

Now comes the real important part. You must set your image tags up to call the swapping function and pass the correct image number to the function. This is how to do it:

<a href='javascript:changeImage(0);'>
<img border='0' src='/images/imageA.jpg'></a>
<a href='javascript:changeImage(1);'>
<img border="0" src="/images/imageB.jpg'></a>
<img border='0' name='mainImage' src='/images/imageA'>

To understand this script completely you have to understand that this isn't a mouseover or rollover. This particular script is from our photo album program which shows eight thumbnails that the user can click on to make the larger, main image change to the clicked thumbnail. What this particular script is doing is switching the main image with the image that is clicked on but this same set up and theory can be used with a mouseover. Note the use of the "name" attribute on the main image, without this nothing works!

Customer Comments

clicking on this will visually collapse the text block directly below it
Lee Ritenour and his staff and fans are very pleased with the work of the DCD Designs team.
Lee Ritenour Staff, leeritenour.com | More Testimonials >>

Latest Articles / Tutorials

clicking on this will visually collapse the text block directly below it |
Our RSS Article Feed Available as RSS Feed!

Check here often for articles & tutorials that will help make your business grow!

| More Articles & Tutorials >>

Partner Comp. & Friends

clicking on this will visually collapse the text block directly below it