0

Is there a method, similar to $(document).ready(), that can be applied to an arbitrary element? For example, if an ajax call sets the content of a DIV and includes a lot of IMG tags, is there a way to trigger a function call when all of the images have completed loading? Something along the lines of:

$.ajax({
    url: '/get/my/page.php',
    dataType: "html",
    success: function(response)
    {
       $('#my_element').html(response);
       $('#my_element').ready(function() {alert('all images loaded');});
        }      
    });

Thanks for your advice.

Chetan Gawai
  • 2,361
  • 1
  • 25
  • 36
Ethan Brown
  • 683
  • 6
  • 11
  • 1
    There are things that give it a decent try, like http://imagesloaded.desandro.com/ (if you're interested in images). – El Yobo Oct 10 '14 at 01:51
  • you might want to refer to this post: http://stackoverflow.com/questions/6571890/check-if-a-given-dom-element-is-ready – Hatjhie Oct 10 '14 at 01:51
  • You could create a script tag and add it after the div element. – dursk Oct 10 '14 at 01:52
  • Document ready would not get image loading either. – epascarello Oct 10 '14 at 01:56
  • Could you not use the .length() method (jQuery) and wrap whatever you want to do in an if statement ,so if element.length for example? – Richlewis Oct 10 '14 at 06:37
  • I ended up going with something similar to Zaptree's solution. Basically, I got the number of img tags in the content, and implementing a load() method on each img instance that incremented a counter. When the counter value equals the number of img tags, I'm done. – Ethan Brown Oct 11 '14 at 03:59
  • Also, I wanted to thank all the responders. You all make this a great community. – Ethan Brown Oct 11 '14 at 04:01

4 Answers4

0

If you're specifically interested in images being loaded, then you can try imagesLoaded, which seems to cover the example case that you mention.

El Yobo
  • 14,823
  • 5
  • 60
  • 78
0

Identical to $("document").ready() -- no, however, there are ways that you can make it work:

  1. Put whatever function you need executed as a callback to the AJAX call:

    $.get("link.php?item=1", function() { //callback function here })

  2. You can have an onchange event listener that triggers whenever the div is being changed and you can specifically trigger a function after a certain number of elements is loaded:

    $("#div").on('change', function() { if ( $("#div").length > DESIRED_NUMBER_OF_ELEMENTS + 1) { //Execute function here } })

The on('change') can be used in any which way you want: it can trigger a function based on the number of elements, based on the nature of elements inside (if it's an image, a link, another div, etc), anything you can think of.

Aroll605
  • 376
  • 1
  • 4
  • 12
0

Something along these lines should do what you want.

onImagesLoaded('#my_element img',function(){
  console.log('images have all loaded')
});
function onImagesLoaded(seletor,callback){
    var $images = $(seletor);
    var count = $images.length;
    $images.each(function(img){
        //create an image
        var tempImage = new Image();
        //set a function for the onload event
        tempImage.onload = function(){
            count--;
            //if the count is 0 it means all images are done loading
            if(count===0){
                callback();
            }
        };
        //set the source to the src of the image.
        tempImage.src = $(img).attr('src');
    });
}
Zaptree
  • 3,763
  • 1
  • 31
  • 26
0

Try

var request = $.ajax({url: "/get/my/page.php", dataType: "html"});

request.done(function (data, textStatus, jqxhr) {
    // parse returned `data` string for html
    var html = $.parseHTML(data),
        // 
        len = html.length,
        div = $("div");
    // do stuff when all images loaded into `div`
    div.on("imgsready", function(e, htmlimgs, divimgs) {
        console.log("ready", htmlimgs, divimgs);
        $(e.target).prepend(divimgs + " images ready<br>" )
    });
    // set `div` html contents to `html` string 
    $.when(div.html(html)
           // return image `on` `load` event
           , $("img", div)
           .load(function(e) {
               // return image `promise` object
               return $(e.target).promise()
           })
    )
    .then(function (el, i) {     
        // if `div` contains `len` length images , call `imgsready` event
        return el.children(i).length === (i.length && len) 
               && el.children(i).eq(len -1).is("*") 
                  ? el.trigger("imgsready", [len, i.length])  
                  // else check again in 1000ms 
                  : setTimeout(function() {
                      el.children(i).eq(len -1).is("*") ?
                      el.trigger("imgsready", [len, i.length])
                      : console.log(el.children(i).length)
                    },1000)
    });       
});

jsfiddle http://jsfiddle.net/guest271314/vhuaen71/

guest271314
  • 1
  • 15
  • 104
  • 177