Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: event for when ajax loaded content is all loaded (including images)

I'm loading in some html via ajax, I need an event to catch on to when the new images are loaded...

becuase it's in a div and not a whole page, I can't use $(window).load(....

I've tried the following but it doesn't work:

$('.banners_col img:last').load(function(){.....
like image 440
Haroldo Avatar asked Dec 20 '10 10:12

Haroldo


1 Answers

You need to target the results of the ajax call before inserting them in the dom.

So you need to use the callback method provided by jQuery for this reason.

$('#load').click(function(){
    // inside the handler that calls the ajax

    //you ajax call here
    $.get('the_url_to_fetch',function(data){

        // create an in-memory DOM element, and insert the ajax results
        var $live = $('<div>').html(data);

        // apply a load method to the images in the ajax results
        $('img',$live).load(function(){
           // what to do for each image that is loaded
        });

        // add the ajax results in the DOM
        $('selector_where_to_put_the_response').html($live.children());
    });

});

example at http://www.jsfiddle.net/gaby/Sj7y2/


If there are multiple images in the ajax response and you want to get notified when all of them are loaded then use this slightly modified version

$('#load').click(function(){
    // inside the handler that calls the ajax

    //you ajax call here
    $.get('the_url_to_fetch',function(data){

        // create an in-memory DOM element, and insert the ajax results
        var $live = $('<div>').html(data);
        // count the number of images
        var imgCount = $live.find('img').length;

        // apply a load method to the images in the ajax results
        $('img',$live).load(function(){
           // what to do for each image that is loaded

           imgCount--;
           if (imgCount==0)
           {
               // the code in here is called when all images have loaded.
           }
        });

        // add the ajax results in the DOM
        $('selector_where_to_put_the_response').html($live.children());
    });

});

example at http://www.jsfiddle.net/gaby/Sj7y2/1/


If you remove the comments and the empty lines, it is not much code :) so do not get intimidated..

like image 149
Gabriele Petrioli Avatar answered Oct 12 '22 12:10

Gabriele Petrioli