javascripthtmljquery

How do I find the number of 'complete' images?


I would like to find the number of images within a specific element(div) that have the property 'complete'(as in the browser has completed loading them).


Solution

  • To answer your immediate question to find images with the complete property, you could use this:

    var container = document.getElementById("div_id"),
        images = container.getElementsByTagName("img"),
        completeImages = [],
        j = images.length,
        i, cur;
    for (i = 0; i < j; i++) {
        cur = images[i];
        if (cur.complete) {
            completeImages.push(cur);
        }
    }
    

    After this code is run, completeImages is an array of <img> elements that have the complete property as true.

    With jQuery, you could use:

    var images = $("#div_id").find("img").filter(function () {
        return $(this).prop("complete");
        // or
        return this.complete;
    });
    

    In this case, images, is a jQuery object (array-like object) of <img> elements that have the complete property as true.

    Instead of checking the complete property, another option is to use the load event to detect when they load and set special data for them:

    $("#div_id").on("load", "img", function () {
        $(this).data("image-complete", true);
    });
    

    and to find out which/how many are loaded:

    $("#div_id").find("img").filter(function () {
        return $(this).data("image-complete");
    });
    

    Note that the load event isn't fully supported/reliable with <img>s: http://api.jquery.com/load-event/ - scroll down to the "Caveats of the load event when used with images" section.