Changing Images with Java Script

By Paulus, 17 December, 2007

While working on a site, I decided to add some Java Script to the menu bar so the site would be more interactive. I wanted the image to change so it gave the appearance as if the user is actually clicking on the button. Being a bit rusty on my Java Script I had to look up how one is supposed to reference an object on the page.

I came across a well written tutorial on how to change the images, but there was one minor problem. The script didn't work. Perhaps it's my web browser, or maybe I'm doing something wrong. When I look at the code itself it doesn't make sense to me. What I kept finding over and over again was this:

document[image_name].src = ...

The problem with the above statement, is that you're trying to find the image by referencing the document array with the image name. That is an array of documents, not an array of images. I played around with this at first thinking that maybe Java Script is a bit funny. The error console in Firefox kept telling me that I was trying to set the property of an object that did not have that property. Further investigation revealed that I was correct in my thinking.

The correct way in setting the source of an image object is actually:

document.images[image_name].src = ...

The best way to change the image when the cursor is over the image is to write a function that can be reused:

function(mouse_over(image_name, image_source)
{
document.images[image_name].src = image_source
}

After including the code in your page, you can use the function like so: