Cycling images with javascript

370 views Asked by At

Why doesn't the second (hawk) image appear when the button is clicked? It goes straight to the else statement showing the ant image.

<!DOCTYPE html>
<html>
    <body>
        <script>
            function changeImg() {
                if (document.getElementById("cycle").src == "fox.jpg") {
                    document.getElementById("cycle").src = "hawk.jpg";
                } else {
                    document.getElementById("cycle").src = "ant.jpg";
                }
            }
        </script>

        <button onclick = "changeImg()">change image</button>
        <img id ="cycle" src ="fox.jpg"/>
    </body>
</html>
3

There are 3 answers

0
Petrashka Siarhei On

document.getElementById("cycle").src always has full url of image (example:https://example.loc/example/fox.jpg) and this is not similar from fox.jpg. You need try another solution.Try use cycle.getAttribute('src')

Example code:

function changeImg() {
          let cycle = document.getElementById("cycle");
               console.log(cycle.src,cycle.getAttribute('src')); // show real value and taribute      
            if (cycle.getAttribute('src') == "fox.jpg") {
                cycle.src = "hawk.jpg";
            } else {cycle.src = "ant.jpg";
            }
        }
2
Daniel On

Please add your script tags at the end of the body to make sure that your dom is rendered before accessing any elements. (like in my example) The problem with your code is, that you need to add a new if for every new image you add. As you noticed yourself, it becomes hard to understand and debug. For something like cycling, use an array and modulo operation on the index of that array.

With this solution, you can add as many images to the images array as you like, without touching the code/logic;

<!DOCTYPE html>
<html>
<body>
  <button onclick="changeImg()">change image</button>
  <img id="cycle" />

  <script>
    var imageElement = document.getElementById("cycle");
    var images = ["fox.jpg", "hawk.jpg", "ant.jpg"]; // add as many images as you want
    var counter = 0;
    imageElement.src = images[counter] // set the initial image

    function changeImg() {
      counter = (counter + 1) % images.length;     
      imageElement.src = images[counter];
    }
  </script>
</body>
</html>
1
Gabriele Petrioli On

Use getAttribute('src') if you want to access the actual contents of the attribute. Otherwise you get the resolved URL.

var cycle = document.getElementById("cycle");
if (cycle.getAttribute('src') == "fox.jpg") {
    cycle.src = "hawk.jpg";
} else {
    cycle.src = "ant.jpg";
}