...

View Full Version : Newbie problem with simple image swap



EnfantSauvage
12-13-2010, 11:12 PM
Lets say I have two images in a box



<body>

<div id="box">

<img src="image1.jpg" id="image1" width="100" height="100" />
<img src="image2.jpg" id="image2" width="100" height="100" />

</div>

</body>


When I click on Image1 I want Image2 to get replaced with a new image, called Image3.

So I tried this code:



var image1 = document.getElementById("image1");
image1.onclick = image1_click ();

function image1_click () {
new_image= new Image
new_image = document.getElementById("image2");
new_image.src="image3.jpg"
}


But instead of replacing the image on click, from some reason it replaces image2 with image3 from start/load.

What should I do to make this work?
Thank you.

DJCMBear
12-13-2010, 11:34 PM
Try this



function imageClick(ID,Image) {
new_image = document.getElementById(ID);
if(new_image) {
new_image.src = Image;
}
}

window.onload = (function(){
document.getElementById("image1").onclick = (function(){
imageClick('image2','image3.jpg');
});
});

EnfantSauvage
12-13-2010, 11:51 PM
Thank you, that works perfectly :thumbsup:



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum