Reputation: 1752
I'm creating a small webapplication with JS/HTML/CSS where the user has a dropdown menu to choose from 13 different images. Option 1 is default, and when the user chooses a different option the application is refreshed and the dimensions of other objects in the application adjust to the dimensions of the new image.
In order to access the image dimensions (height and width) of the 13 different images an JS loop starts and stores the dimensions in two arrays.
var height_array = []
var width_array = []
for (i = 1; i <= 13;i = i + 1) {
var img = new Image();
if (i <= 9){
img.src = "img/rehe/RE0"+i+"/001.png";
}
else{
img.src = "img/rehe/RE"+i+"/001.png";
}
height_array.push(img.height);
width_array.push(img.width);
}
What I dont understand, is that the loop is sucessfull only part time, at times the arrays are empty or only partially populated. Naturally, the application is then built up all wrong.. A refresh helps in this case, but it is still anoying.
I have a preversion of this very simple application here: http://wieselundco.ch/plenum2/index.html Thanks in advance!
Upvotes: 2
Views: 31
Reputation: 318202
The image has to load before you can get the dimensions
var height_array = []
var width_array = []
for (i = 1; i <= 13;i = i + 1) {
(function(j) {
var img = new Image();
img.onload = function() {
height_array[j] = img.height;
width_array[j] = img.width;
}
if (img.complete) img.onload();
if (j <= 9){
img.src = "img/rehe/RE0"+j+"/001.png";
} else {
img.src = "img/rehe/RE"+j+"/001.png";
}
})(i);
}
Upvotes: 2