I’m very new to web programming and jQuery. I want to load images and arrange them in a grid. However, the number of images to be loaded is not fixed. I have an array, img_arr, with the url and an id for each image.
The code that loads and positions images is like this:
var t = 0;
var l = 0;
for (i = 0; i < img_arr.length; i++) {
var img = new Image();
$(img)
.attr('src', img_arr[i]['url'])
.attr('id', img_arr[i]['id'])
.load(function(){
$('#container').append( $(this) );
// Your other custom code
$(this).css( {
"position": "absolute",
"top": t + 'px',
"left": l + 'px'
});
});
l = l + 50;
if (l > 300) {
t = t + 50;
l = 0;
}
}
But, the images get placed on top of each other at the final offset location. Anyone know why this happens?
Mwahaha! [Evil laughter]
There’s an error here, a common, insidious error, one that has nothing to do with images, or CSS, or jQuery. It’s the late-binding error in Javascript.
The OP uses the variables
tandlto mean “top” and “left” (incidentally, OP, what is wrong withtopandleftas variable names), incrementing them in a loop and invoking them at a callback. Buttandlare late bound. When the onload functions are called, those variables are set to their final values, not the values they had when the image tag was created.And so, “the images get placed on top of each other at the final offset location”.
Try this: