user1258829
user1258829

Reputation: 73

Image changing loop not working

I have written a JavaScript that is supposed to change my header image every three seconds. For some reason nothing happens when I'm opening my page.

Can anyone see what I'm doing wrong?

HTML:

<html>
    <head>
        <link rel="stylesheet" type="text/css" href="styles.css">
        <script src="changeImage.js"></script>
        <title>Mikael Mattsson</title>
    </head>
    <body>
        <div class="header">
            <img id="headerImg" src="images/header-image.png" alt="Header image" width="100%" hight="100%">
        </div>
    </body>
</html>

JavaScript:

var images = [];
images[0] = "images/header-image.png";
images[1] = "images/header-image2.png";
var x = 0;
function imageChanger(){
    var img = document.getElementById("headerImg");
    img.src = images[x];
    x++;
    if (x > images.length){
        x = 0;
    }

    setTimeout("imageChanger()", 3000);
}

Upvotes: 0

Views: 131

Answers (4)

Tim Coulter
Tim Coulter

Reputation: 459

You're close. You need to change two things.

First, you need to call the imageChanger function at least once to kick off the code. At the end of your script, add:

imageChanger();

Your code may work from there. However, instead of passing a string to setTimeout(), you should instead pass a reference to the function itself:

setTimeout(imageChanger, 3000);

You should be all set. Let me know if you have issues.

Upvotes: 1

clentfort
clentfort

Reputation: 2504

You call the setTimeout inside the function but never call the function. So the timeout is never set, hence the function is not called through the timeout.

I recommend using setInterval above setTimeout in your case since you want to have the function executed repeatedly. Also you could improve the way you increase x.

var x = 0;
function imageChanger() {
    var img = document.getElementById("headerImg");
    x = (x + 1) % images.length; // Make sure x is never larger than images.length
    img.src = images[x];
}

// Start calling the function after a delay of 3000ms
setInterval(imageChanger, 3000);​​​​

I also recommend using a better name than x for your counter variable, but that is up to you!

Upvotes: 1

mplungjan
mplungjan

Reputation: 177950

Remove

setTimeout("imageChanger()", 3000);

And add

window.onload=function() {

  setInterval(imageChanger, 3000);
}

Outside the function

And as pointed out, change > to >=

Upvotes: 0

hjpotter92
hjpotter92

Reputation: 80639

  1. x > images.length should be x >= images.length.
  2. setTimeout("imageChanger()", 3000); must be changed to setTimeout(imageChanger, 3000);

Upvotes: 3

Related Questions