Mac Forums

Mac Forums (
-   Web Design and Hosting (
-   -   Javascript Image Change (

FinnIII 04-18-2008 07:13 AM

Javascript Image Change
I have found a code that changes the background image of a page. Is it possible to adapt it to change an image on the page?


<script language="JavaScript">

// Copyright 2001 by
// Please do *not* remove this notice.

var backImage = new Array();

backImage[0] = "../gallery_pages/images/stupid/full-32 King Stupid Main Set.JPG";
backImage[1] = "../gallery_pages/images/stupid/full-33 King Stupid Control Desk.jpg";
backImage[2] = "../gallery_pages/images/stupid/full-34 King Stupid Main Set Rev..JPG";

function changeBGImage(whichImage){
if (document.body){
document.body.background = backImage[whichImage];


Can you help?

Thyamine 04-18-2008 08:16 AM

There are a lot of ways to change the image on a page. This is simply using javascript to refer to the document background object. You can do the same thing with an image by giving it an ID (a name), and then use Javascript to find it and change the src.

I couldn't find the right tutorial I wanted to link to, but you can certainly google it and find one that makes sense to you.

knightlie 04-18-2008 09:10 AM


var img;

img = document.getElementById('imageID');
img.src = '';

That's off the top of my head, but it's something similar. The IMG tag needs an id="imageID" for this to work:


<img id="imageID" src="image.jpg" />
You can also pre-load the new image into a variable and assign it later, but the code is slightly different. As Thyamine said there are bazillions of tutorials on the web for doing this

Thyamine 04-18-2008 10:44 AM

What Knightlie has entered is pretty much what you need.

One thing to note, case sensitivity can be important, and I have a tendency to type getElementByID (capital ID) instead of getElementById, and it always takes me forever to track down where the heck the javascript error I'm getting is from.

giulio 04-18-2008 12:05 PM

Less code:


Or if you're using prototype/scriptaculous, even less:



FinnIII 04-18-2008 05:28 PM

I kind of get the logic, but It isn't working for me.

In the head, I have:

<script language="JavaScript">

And the Body:

<img id="imageID" src="../gallery_pages/images/stupid/full-32.JPG"/>

<a href="javascript:'imageID'.src='../gallery_pages/images/stupid/full-33 King Stupid Control Desk.jpg'"><img src="../gallery_pages/images/stupid/thumbs15/thumb-full-33" border="0" /></a>
What needs correcting? Oh, and you have been a big help so far :)

Thyamine 04-19-2008 07:45 AM

getElementByID should be getElementById (lowercase d).

All times are GMT -4. The time now is 12:51 AM.

Powered by vBulletin
Copyright ©2000 - 2015, Jelsoft Enterprises Ltd.