skip to Main Content

This is the code I’m using to get all loaded images:

$("img").on('load', function() {
  console.log('Image Loaded'); 
}).each(function() {
    if(this.complete){
        //$(this).trigger('load'); 
        var img = $(this).attr('src');
        console.log(img);
    } 
});

but it’s not working with those that are loaded with ajax afterwards, so I tried:

$(document).on('load', 'img', function(){
  console.log('Image Loaded'); 
}).each(function() {
    if(this.complete){
        //$(this).trigger('load'); 
        var img = $(this).attr('src');
        console.log(img);
    } 
});

but it’s not doing anything, what would be the correct way? I need to manipulate the parent divs of each image that is freshly loaded, so getting just all images period on every ajax load would be overkill and not elegant

3

Answers


  1. How about this?

    $(document).on('load', 'img', function(){
         console.log('Image Loaded');
         var parent = $(this).parent(); //or .parents('div') or .closest('div'), etc..
         //do something with parent
    });
    
    Login or Signup to reply.
  2. I will suggest that you create a function for getting images and also call the same function after ajax execution.

    Edit

    Pass an id or class string present in document or returned ajax data to limit the scope of the function

    function getImages(id) {
        $('#' + id).find("img").on('load', function() {
            console.log('Image Loaded'); 
        }).each(function() {
            if(this.complete) {
                //$(this).trigger('load'); 
                var img = $(this).attr('src');
                console.log(img);
            } 
        });
    }
    
    getImages('outsideAjax'); // call during normal execution. outsideAjax is an id within your html document but not in the returned ajax data
    
    $.ajax({
        // ajax settings
    }).done(function() {
        // post ajax code
        // append returned data to document
        getImages('insideAjax'); // recall after successful ajax execution and appending of returned data. 'insideAjax' is an id inside your return ajax data 
    }).fail(function(jqXHR, textStatus, errorThrown) {
        // report error
    });
    
    Login or Signup to reply.
  3. This is how I solved it:

    <img src="' + picUrl + '" onload="checkPic('' + picUrl + '', this.naturalHeight, this.height);" class="pic">
    

    Inside AJAX response.

    I think it’s self explanatory, works perfectly!

    In the checkPic functuion I find this element by the src and get the parent elements and so on.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search