Javascript To Change Image On Link Click

I recently decided to add the ability for guests to request a new captcha image (or refresh the captcha image) in my guestbook script for when it was to hard for visitors to read. As usual trying to find some instructions to do this proved useless so I had to figure it out myself. I thought I would explain how it’s done here for anyone else wanting to do this and believe me it’s very very simple.

Ok first thing we need to do is give a name to the image we are going to by replacing/changing so we add a name. For the guestbook script I added added name=”lazCaptcha” to the image tag.

eg:

<img src="http://domain.com/path/image.jpg" name="NAMEFORIMAGE" alt="" />

Next we need to create the link that the viewer clicks on to replace/change the image and for that I used this bit of code:

<a href="#" onclick="reloadImage('NAMEFORIMAGE'); return false;">request another image</a>

Notice how I put the name of the image into the Javascript? Thats so we can use this code multiple times on a single page.

Next we need the Javascript and it is very simple. We just create a random number to add to the image url to prevent it showing the cached image and then tell the browser to change the image. I’ll show two examples. The first is just when we want to display a random image and the second is how I display a new captcha image with the same code.

Random Image:

function reloadImage(imageName)
{
var myImages=new Array();
myImages[0]="sun.jpg";
myImages[1]="moon.jpg";
myImages[2]="stars.jpg";
// Create a random number between 1 and one greater than the number of items in the array
var randomImage = Math.floor(Math.random() * (myImages.length + 1));
randomImage--;
// Change the image
document.images[imageName].src = 'http://yoursite.com/path/to/' + myImages[randomImage];
}

Captcha Image:

function reloadImage(imageName)
{
// Create a random number between 1 and 1000
var randomnumber=Math.floor(Math.random()*1001);
// Change the image
document.images[imageName].src = 'http://yoursite.com/path/image.php?hash=OURHASH&rand=' + randomnumber;
}

OURHASH? What’s that? :-? Well if you are planning to refresh a captcha image then I’m guessing you have generated the form the image is displayed in and so you can just use the variable you used for the hash in the image tag to put the hash in the javascript image tag. Or you could just change that line to

document.images[imageName].src = document.images[imageName].src + '&rand=' + randomnumber; // Change the image

And thats it. See how simple it is to do? ;-)