Click to See Complete Forum and Search --> : ImageSwap w/ an if statement
sevenz
07-15-2003, 07:00 PM
Hi All,
Looking for a script that would allow an onclick imageswap to determine the following.
if the image is image1.gif, then swap it to image2.gif, but if the image is image2.gif, then swap it to image1.gif
The default image would be image1.gif
So for the first click i can easily make it swap to 2, but i want it to swap back upon a secondary click.
Suggestions?
http://www.fishingvancouver.com
Script will run on left side menu bar.
Charles
07-15-2003, 08:21 PM
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="Content-Script-Type" content="text/javascript">
<title>Example</title>
<img src="http://www.bettiepage.com/images/photos/bikini/bikini1_a.jpg" alt="[Bettie Paige]" onmouseover="this.src = /bikini1_a.jpg$/.test(this.href) ? 'http://www.bettiepage.com/images/photos/bikini/bikini2_a.jpg' : 'http://www.bettiepage.com/images/photos/bikini/bikini1_a.jpg'">
Khalid Ali
07-15-2003, 08:24 PM
in the head section of the page pout the following code
<script type="text/javascript">
//preload both images
var img1,img2;
if(document.images){
img1 = new Image();
img1.src = "images/image1.gif";
img2 = new Image();
img2.src = "images/image2.gif";
}
//function to perform the swap
function swapImage(){
//get referrence to the image element
var img = document.getElementById("imgEl");
//now perform the test
if(img.src.indexOf("image1)>-1){
img.src = img2.src;
}else{
img.src = img1.src;
}
}
</script>
now in the html part of the page (uin the body of the page)
<input type="button" value="Swap Image" onclick="swapImage();">
<img id="imgEl" src="images/image1.gif" alt=""/>
sevenz
07-16-2003, 05:23 PM
Hi Khalid,
Thank You very much, I had to fiddle a bit to get the right combination, but was able to make the script work, as well add on to it further variables that effect up to 4 other images at the same time. Just one note, for further reference,
if(img.src.indexOf("image1)>-1){
This line above needed to read
if(img.src.indexOf("images/image1")>-1){
Once i figured that out, everythign else was smooth sailing. Thank you so much.
Darrin