-1

Simply put, I have three images, and I'd like to cycle through them when I click on the image. In other words, I want the img src to change to the next specified image when it is clicked on. However, this doesn't happen. Keep in mind all of the images I have are in the same folder as my html code, and each image loads just fine by themselves, they just won't cycle through.

Here is my code:

<!Doctype html>
<html>
<head>
</head>
<body>

<p>Hello world</p>

<img onclick="changePic()" id="pika" src="pichu.gif" alt="pichu">

<script>
    function changePic() {
    var pika = document.getElementById("pika").src;

    if(pika == "pichu.gif") {
        pika = "pikachu.gif";
    } else if (pika == "pikachu.gif") {
        pika = "raichu.gif";
    } else  {
        pika = "pichu.gif";
    }
}
</script>

</body>
</html>
Brandon Copeland
  • 125
  • 1
  • 2
  • 9
  • Have you debugged your code to see what the `pika` variable is when you click the image? – j08691 Jul 01 '15 at 15:47
  • How might I go about doing that? – Brandon Copeland Jul 01 '15 at 15:49
  • By logging the variable to the console, or alerting it. See http://stackoverflow.com/questions/988363/how-can-i-debug-my-javascript-code – j08691 Jul 01 '15 at 15:50
  • add "alerts" or "console.log" into the function "changePic()", or if you use chrome, in "Developer tools" section Source, you can add breakpoints into the changePic() function whenever it's called – Zander Jul 01 '15 at 15:51
  • Okay. at the bottom of my script, I added "console.log(pika)". On every click, the console logs "pichu.gif." – Brandon Copeland Jul 01 '15 at 15:57

1 Answers1

1

the source property of your image is not a reference property. so changing the variable pika doesn't effect the src property of the pika element.

if you set the pika variable to the element itself, then check and set the SRC values in your if else statements you should be good.

var pika = document.getElementById("pika");
if (pika.src == "pichu.gif") {
   pika.src = "Pikachu.gif"
}  etc...

Edit:

Forgot to point out also that your SRC property may not be just the file name but could also be the patch to the file name depending on how you have your HTML and folder structure setup.

Peter Lange
  • 2,786
  • 2
  • 26
  • 40
  • I changed it per your suggestion, and still doesn't work, but something changed. The console is still logging the directory name of the "pichu.gif" image, but when I click the image now, I notice that the same gif is just reloaded. Initially, I actually did do it the way you suggested and it did the same thing. Fiddling with it, I ended up suspected that the reason was that it's actually going directly to the else statement and loaded the same gif as if it's a different one. – Brandon Copeland Jul 01 '15 at 16:05