sujal sujal - 7 months ago 11
Javascript Question

Show all images only after their complete load


Possible Duplicate:

jQuery event for images loaded




In

<div id="all-images">
<img src="images/1.jpg">
<img src="images/2.jpg">
<img src="images/3.jpg">
<img src="images/4.jpg">
<img src="images/5.jpg">
<img src="images/6.jpg">
</div>


I want to show all Images of id="all-images" only when all the images inside this id will load completely (Jquery).

And before loading all images this section shows "Loading.." text

Answer

Assuming your div is pre-hidden:

$("#loadingDiv").show();
var nImages = $("#all-images").length;
var loadCounter = 0;
//binds onload event listner to images
$("#all-images img").on("load", function() {
    loadCounter++;
    if(nImages == loadCounter) {
        $(this).parent().show();
        $("#loadingDiv").hide();
    }
}).each(function() {

    // attempt to defeat cases where load event does not fire
    // on cached images
    if(this.complete) $(this).trigger("load");
});