PDA

View Full Version : Swapping Image OnClick - Please Help



me_myself
09-11-2007, 07:47 PM
I recently came across the below code - it is for changing the image OnClick - I need to know how to change it back to the original image when you click on the image again.

Image 1 onclick changes to Image 2 onclick changes to Image 1.....


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>
<title></title>
<script language="JavaScript" type="text/javascript">
<!--

function Swap(obj){
obj.src='http://www.vicsjavascripts.org.uk/StdImages/Two.gif';
setTimeout('document.getElementById(\'Img2\').src=\'http://www.vicsjavascripts.org.uk/StdImages/Two.gif\';',2000);

}
//-->
</script></head>

<body>

ClickMe >> <img src='http://www.vicsjavascripts.org.uk/StdImages/One.gif' width=100 height="100" onclick="Swap(this);" >
<img id="Img2" src='http://www.vicsjavascripts.org.uk/StdImages/One.gif' width=100 height="100" >
</body>

</html>

jscheuer1
09-12-2007, 03:41 AM
Well, it isn't really clear what you are ultimately after. But try this:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>
<title></title>
<script type="text/javascript">


function Swap(obj){
var other=document.getElementById('Img2');
obj.src=(Swap.swaped=!Swap.swaped)? 'http://www.vicsjavascripts.org.uk/StdImages/Two.gif' : 'http://www.vicsjavascripts.org.uk/StdImages/One.gif';
setTimeout(function(){other.src=obj.src;},2000);
}

</script></head>

<body>

ClickMe >> <img src='http://www.vicsjavascripts.org.uk/StdImages/One.gif' width=100 height="100" onclick="Swap(this);" >
<img id="Img2" src='http://www.vicsjavascripts.org.uk/StdImages/One.gif' width=100 height="100" >
</body>

</html>

me_myself
09-12-2007, 03:12 PM
I wanted to swap two images on click. The code you gave works. Thanks a lot.