0

Hi I show a div on click, but the content of this div is some pretty big images and I want to add a preloader meanwhile the div is loading... I've been trying with jquery .load but can only get it to work when page first is loaded and not on click.

so i want a loader gif to be presented when aboutclick is clicked and hidden when all the content id #aboutcontent is loaded.

function aboutClick(){
        $('#workContent').fadeOut(400,'easeInQuint');
        $('#aboutContent').fadeIn(400,'easeInQuint');       
 };

$('#aboutContent').load(function() {
   jQuery("#gif").show(100);
});
  • 2
    If it is the image that is taking time to load, you'll have to hook load on image. see http://stackoverflow.com/questions/10790226/jquery-image-load-callback – U.P Aug 15 '14 at 12:00
  • 1
    the thing is im using background images, and it's the entire div that takes time to load.. i don't know how to attach a .load event on a div – user3803628 Aug 15 '14 at 12:10
  • 1
    i've tried to do this but it doesn't work $('#aboutContent').load(function() { jQuery("#gif").show(100); }); – user3803628 Aug 15 '14 at 12:10

1 Answers1

1

You can bind the load event on images, it will fire as soon as the image is loaded.

$("#aboutContent img").load(function(){
  $("#loadergif").fadeOut(400);
});

This will fail, however, because if you load multiple images, your loader gif will hide as soon as the first image is loaded.

Thats why you will need to keep a counter on the amount of images, and hide it after they all finished loading.

Taken from: jquery callback after all images in dom are loaded?

$(function() {
    function imageLoaded() {
       // function to invoke for loaded image
       // decrement the counter
       counter--; 
       if( counter === 0 ) {
           // counter is 0 which means the last, so hide the loadergif
               $("#loadergif").fadeOut(400);
       }
    }
    var images = $('img');
    var counter = images.length;  // initialize the counter

    images.each(function() {
        if( this.complete ) {
            imageLoaded.call( this );
        } else {
           $(this).one('load', imageLoaded);
        }

    });
});

Good luck.

Community
  • 1
  • 1
Milanzor
  • 1,920
  • 14
  • 22