TDonnally
TDonnally

Reputation: 67

Changing src of image by iterating through a list

I am trying to have an image change every tenth of a second. I have written a script based off other responses on here and it is still not working. Here is the script:

var images = Array();
var index = 0;
images = ["rock.png", "paper.png", "scissors.png"];
var opponent = document.getElementById("opps");

setInterval(myMethod, 100);

function myMethod( ){
    opponent.src = images[index];

    if (index <= 1){
        index++;
    }
    else{
        index = 0;
    }
}

Here is the tag:

<img src = "" id ="opps"/>

Upvotes: 0

Views: 61

Answers (3)

symlink
symlink

Reputation: 12209

Your code worked, the strings in the images array were relative so maybe you didn't have them in your project. I've simplified a few things, first I initialize and declare the images array in the same expression, and second, I turned your if statement in myMethod() into a ternary expression:

let index = 0
const images = [
  "http://placekitten.com/200/200", 
  "http://placekitten.com/210/210", 
  "http://placekitten.com/220/220"
]

const opponent = document.getElementById("opps");

setInterval(myMethod, 1000)

function myMethod(){
    opponent.src = images[index];

    index = index <= 1 ? index + 1 : 0
}
<img src="" id="opps"/>

Upvotes: 0

Shiny
Shiny

Reputation: 5055

You can do index % images.length to infinitely loop over the array - when you go over the index, it'll just wrap back around

Also, you should use let a = [] to create an empty Array. You don't have to, but it's good practice - Read more

Finally, 100 miliseconds is probably a little too often to change an image src, about 1 - 5 seconds should be plenty in most cases

var images = ["rock.png", "paper.png", "scissors.png"];
var index = 0;
var opponent = document.getElementById("opps");

setInterval(myMethod, 100);

function myMethod( ){
    opponent.src = images[index % images.length];
    index += 1;
    
    console.log(opponent.src);
}
<img src = "" id ="opps"/>

Upvotes: 1

TDonnally
TDonnally

Reputation: 67

I figured it out. To anyone else with this error it is due to having your script run before your html. Run script after your img.

Upvotes: 1

Related Questions