1

I wanted write preloader images and I was stuck on the checking already lodead images:

var imgContainer = [];

$(this).find('img').each(function() {
    imgContainer.push({
        image: $(this)
        // other properties
    })
});

setInterval(function() {
    console.log(imgContainer[0].image.complete);  // undefined
}, 2000);

but this solution worked (without objects in array):

var imgContainer = $(this).find('img');

setInterval(function() {
    console.log(imgContainer[0].complete)         // true
}, 2000);

Why it's not working?

5
  • 2
    event sounds like a really bad choice for that argument name. You do know you can use this and make the function argument-less? Commented Apr 14, 2012 at 20:52
  • Well, those two lines are not identical, is there a complete property of image? Commented Apr 14, 2012 at 20:56
  • @ThiefMaster You're right. I changed it, but this still doesn't solve the problem. Commented Apr 14, 2012 at 21:03
  • While event is semantically incorrect it was used in the proper way as the second argument in the itterative function passed to the function each on a jQuery collection is the element in question for the relevant iteration. Commented Apr 14, 2012 at 21:09
  • As a side note, checking if something loaded with setInterval probably isn't the way to go, but now you know what you did wrong, implement @Engineer s solution instead ;) Commented Apr 14, 2012 at 21:15

2 Answers 2

1

Instead of using setInterval ,for checking whether all images are loaded, just replace your above code with this code:

(function(that){
    var remains = 0;        
    var loadHandler = function(){
       if(--remains == 0){
          console.log('All images are loaded !!!');
       }   
    };

    $(that).find('img').each(function() {
         if( !this.complete ){
             remains++;
             $(this).load(loadHandler);
         }
    });        
})(this);
Sign up to request clarification or add additional context in comments.

Comments

0

In your code you're trying to access the 'complete' attribute on the jQuery object while it will not have this. Try accessing the complete attribute on the DOM element itself instead.

I believe this code should work better:

var imgContainer = [];

$(this).find('img').each(function() {
    imgContainer.push({
        image: $(this)
        // other properties
    })
});

setInterval(function() {
    /* imgContainer = array with objects, [0] = get first element */
    /* image = jQuery collection, [0] = get dom element of the first item in the collection */
    console.log(imgContainer[0].image[0].complete);  
}, 2000);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.