1

I wanted to make a short cut for writing all the onload functions for my images by looping through an object's variables called GameImages. I'm not sure why the images aren't being loaded when I look in the developer console in chrome. Is the for loop interrupting the loading of the images? How can I load the images in a loop instead of writing each onload function?

var i = 1; //set increment variable

var GameImages = { //object to hold each image

    game1 : new Image(),
    game2 : new Image(),
    game3 : new Image(),
    game4 : new Image(),
    game5 : new Image(),

};

for(gameImage in GameImages) { //loop through each image

    gameImage.onload = function () { //set the onload function for the current image

        gamePosters.push(gameImage);
        console.log(gamePosters.length); //print out the new size of the gamePosters array

    };

    //give source of image. (my images are named game1.jpg, game2.jpg, etc.)
    gameImage.src = "images/assets/posters/games/game" + i + ".jpg";

    i += 1; //increment i
}

1 Answer 1

1

It is because you're for (gameImage in GameImages) loop is looping through each of your GameImage object's properties (i.e. gameImage is first "game1", then "game2", etc.). Change your code to:

for (game in GameImages) {

   var gameImage = GameImages[game]; // This will get your actual Image
   gameImage.onload = function () { 

       gamePosters.push(gameImage);
       console.log(gamePosters.length); 

   };

   //give source of image. (my images are named game1.jpg, game2.jpg, etc.)
   gameImage.src = "images/assets/posters/games/game" + i + ".jpg";

   i += 1; //increment i
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.