Reputation: 351
I have 6 pictures of the lovely Serena Williams, I've been researching how to change the images every time I click on them. However the code is not working, please help me identify whether I've made a logic or syntax error:
<html>
<head>
<title>SerenaWilliams</title>
</head>
<body>
<img src="http://1.bp.blogspot.com/-hGUyOlpoeB0/UROyeHgMXcI/AAAAAAAAAZ4/L32zLAQvQj0/s1600/Hot-Serena-Williams+_sexy+16.jpg" id="serenaGallery" onclick="changeImage" />
</body>
<script type="text/javascript">
function changeImage() {
var currentImage = document.getElementById("serenaGallery").src;
var image1 = "http://1.bp.blogspot.com/-hGUyOlpoeB0/UROyeHgMXcI/AAAAAAAAAZ4/L32zLAQvQj0/s1600/Hot-Serena-Williams+_sexy+16.jpg";
var image2 = "http://usatthebiglead.files.wordpress.com/2011/04/serena-williams-is-big-boned.jpg";
var image3 = "http://www.strangecosmos.com/images/content/109963.jpg";
var image4 = "http://1.bp.blogspot.com/-HiJxcIjMmFg/UWo9JtbfCEI/AAAAAAAAF1g/aUU42F3V9Ic/s1600/Serena+Williams+Hot+2013+04.jpg";
var image5 = "http://mystarclub.com/wp-content/uploads/2012/11/Serena-Williams-is-a-Bikini-Babe.jpg";
var image6 = "http://1.bp.blogspot.com/-vCsx4sswzeM/UA5GtbEwJ1I/AAAAAAAAACE/tMiP_p-0rB0/s1600/serena+williams+tennis+ball+in+butt.jpg";
if (currentImage==image1){ currentImage=image2; }
if (currentImage==image2){ currentImage=image3; }
if (currentImage==image3){ currentImage=image4; }
if (currentImage==image4){ currentImage=image5; }
if (currentImage==image5){ currentImage=image6; }
else { currentImage=image1; }
}
</script>
</html>
Upvotes: 0
Views: 6067
Reputation: 14477
First of all, you need to modify the onclick attribute so it will actually execute the function:
onclick="changeImage()"
The command
var currentImage = document.getElementById("serenaGallery").src;
just stores the source attribute of the image in a variable; it doesn't reference it.
Also, you have to change all if
statements to else if
or the function will change image1 to image2, then to image3, etc.
This would work:
var currentImage = document.getElementById("serenaGallery");
...
if (currentImage.src == image1){ currentImage.src=image2;}
else if (currentImage.src == image2){ currentImage.src=image3;}
...
Lastly, using an array for the image sources would allow you to condense the if
statements into a single for
loop. Not really needed for six images, but better if you want to add more.
Upvotes: 2