Reputation: 2263
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
}
Upvotes: 1
Views: 586
Reputation: 16518
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
}
Upvotes: 1