0

I'm not sure why my function is not returning data.

loadingImages = function (id)
{
    var totalImages = $(id+" img").length;
    var imagesLoaded = 0;
    var result = null;

    $(id).find('img').each(function(elem) {
        var fakeSrc = $(this).attr('src');

        $(this).attr("src", fakeSrc).load(function() {

            imagesLoaded++;

            if (imagesLoaded >= totalImages) { 
                result = true;
            } else {
                result = false;
            }
        console.log(result);
        });

    }); 
    return result;
}


var $id = "#elem";
var rr = loadingImages($id);
console.log(rr);

Any help would be appreciated, this is just personal studying code so I'm in no rush.

Michael Doye
  • 8,063
  • 5
  • 40
  • 56

1 Answers1

0

.load will not fire immediately, so your result will always be null. You should change your code so that the function accepts a callback:

loadingImages = function (id, cb) {
    var totalImages = $(id+" img").length;
    var imagesLoaded = 0;
    var result = null;

    $(id).find('img').each(function(elem) {
        var fakeSrc = $(this).attr('src');

        $(this).attr("src", fakeSrc).load(function() {
            imagesLoaded++;

            if (imagesLoaded >= totalImages) {
                result = true; 
                cb(result);
            }
        });

    }); 
}


var $id = "#elem";
loadingImages($id, function(rr) {
    console.log(rr);
});
Wex
  • 15,539
  • 10
  • 64
  • 107