-5

why can't this code work ? I'm trying to change an image every 4 seconds... I really don't understand, everything should work correctly.

<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
function Falcon0408()
{
document.getElementByTagName('img');


if (document.getElementByTagName('img').src='img1.png')
{
document.getElementByTagName('img').src='img2.png';
}




else if (document.getElementByTagName('img').src='img2.png')
{
document.getElementByTagName('img').src='img3.png';

}

else if (document.getElementByTagName('img').src='img3')
{
document.getElementByTagName('img').src='img1.png';
}
}
</script>

</head>
<body>
<script>
setTimeout(Falcon0408(),400);
</script>
<img src='img.png'/>


</body>
</html>
Thomas
  • 19
  • 1

1 Answers1

2
  1. It's getElementsByTagName - "elements" is plural because you get all of the ones with that tag.
  2. You're using the assignment operator = instead of comparison == or ===.
  3. The actual image source in the HTML is just "img.png" so it will never match any of your "if" statements.
  4. Not an error, but a tip: "Don't Repeat Yourself." Get the image's attribute once, and store it in a variable, then check against that variable.
  5. Give your image tag a unique ID so you can target it directly with getElementById (note it's "Id" not "ID"). What if you have multiple img tags on the page? You probably don't want all of them to change.

Code:

<img id="myImg" src="img1.png"/>

function Falcon0408()
{
    var image = document.getElementById('myImg');

    if (image.src === 'img1.png')
   {
       image.src = 'img2.png';
   }

   else if (image.src === 'img2.png')
   {
       image.src='img3.png';
   }

   else if (image.src === 'img3')
   {
      image.src='img1.png';
   }
}
  1. What will you do when you want to cycle through 20 or 1000 images? Will you keep adding if/else blocks?

A better approach would be to have an array of images (or just know exactly how many photos you have in the folder) and use a loop to change the source based on the number of images in the array. That way you don't have to keep adding else/if statements every time you want to add a new image ... but that's beyond the scope of this question.

  1. If you want this to loop, this won't work. See this answer for how to use setInterval(), or how to include another call to setTimeout() inside the function so that it keeps going.
Community
  • 1
  • 1
mc01
  • 3,750
  • 19
  • 24