i am trying to order some images in columns based on their height and i have the following code.
the problem is that even though imgHeights.length works fine, imgHeights[i] (in the redrawThumbs function) doesn’t return a value.
what am i doing wrong? thanks =)
function redrawThumbs(imgHeights){
// some irrelevant code here
// initialise an array that will hold all the column's heights
var colHeights = new Array(cols);
for(a=0; a <= colHeights.length - 1; ++a){
colHeights[a] = 0;
}
// take each image's height and add it to the shortest column
for(i=0; i <= imgHeights.length - 1; ++i){
var shortestCol = 0;
for(c=0; c <= colHeights.length - 2; ++c){
if(colHeights[c+1] < colHeights[c]){
shortestCol = colHeights[c+1];
}
}
alert("imgHeights[" + i + "] " + imgHeights[i]);
colHeights[shortestCol] += imgHeights[i];
}
}
// make an array of image heights
var imgHeights = new Array(totalThumbs);
for(i=1; i <= totalThumbs; ++i){
var img = new Image();
img.onload = function(){
imgHeights[i-1] = this.height;
}
img.src = i + ".jpg";
// call function that orders the images
redrawThumbs(imgHeights);
One of the issues is that the
ivariable is captured by reference, not by value so, for all the callback ofimg.onloadis getting the same value ofi. Consider changing theonloadassignment to,this captures a copy of the value of
iat the point of auto-execute function execution and callsallLoaded()after all the images have been loaded.