0

i have a problem while incrementing a variable and adding new data to array in the jquery load function. I think that incremention and array manipulation is done when all images are loaded. But I need to use imgCount variable futher in the code. So could you give me the solution? Sorry for my bad english )))

var imgObject = $('#temp_img img'); // dinamicaly loaded images 

var readyImages = [];
var imgCount = 0;

$(imgObject).bind("load", function() {

    if (this.width > 200 && this.height > 200) {

        readyImages.push(this.src);
        imgCount++;
    }

});

alert(imgCount) // returns 0, though must return 3
Seth
  • 6,240
  • 3
  • 28
  • 44
mXaln
  • 105
  • 11
  • Try running a `console.log(this);` just before your IF to make sure the image matches the condition. – Seth Jan 19 '12 at 16:38
  • 1
    the alert(imgCount) will fire before the images are loaded, so at the time it fires, imgCount is still 0. Try adding an alert(imgCount) inside the load function, you'll see it fire once per load. – Chris Carew Jan 19 '12 at 16:39
  • Check out the warnings in the jquery docs: http://api.jquery.com/load-event/ ("Caveats of the load event when used with images"). As well, if you're on jquery 1.7+, you shoul be using `.on()` instead of `.bind()`. – Marc B Jan 19 '12 at 16:40

1 Answers1

1

The callback you define will run asynchronously, while the alert statement will be run immediately. What you would need to do is first count the number of images found, then trigger some functionality when all of them are loaded. Something like:

var imgObject = $('#temp_img img'); var imgCount = imgObject.length - 1; var imgLoadedCnt = 0; var readyImages = []; $(imgObject).bind("load", function() {

if (this.width > 200 && this.height > 200) {
    readyImages.push(this.src);\
    imgLoadedCnt ++;
    if (imgLoadedCnt == imgCount) {
        someFnToRunOnLoaded();
    }
}

});

Robert
  • 2,441
  • 21
  • 12
  • Thank you Robert, you helped me to understand that I went wrong direction. If I load more than 50 images for example it takes too long for all of them to be loaded completely before I output smth to client. So I totaly redisigned my functions. – mXaln Jan 19 '12 at 23:54