0

I am trying to call a function after the image loads completely in DOM.

The image structure is created dynamically on AJAX call success and the image url is also added in success using the result of API call.

Problem: I want to call a function after the image loads completely in DOM. To do this I have used JQuery load event.

Function which is called on load.

function carouselHeight() {
    $('.home-banner-img-container').each(function() {
        var $this = $(this);
        var dynamicheight = $(this).parent();
        var sectionInnerHeight = $this.innerHeight();
        dynamicheight.css({
            'height': sectionInnerHeight
        });
    });
}

I have tried below steps but it didn't worked

$(window).on('load', function() {
   carouselHeight();
});

$(window).on('load', 'img.image-preview', function() {
  carouselHeight();
});

$(document).on('load', 'img.image-preview', function() {
  carouselHeight();
});

The first method $(window).on('load', function() {}) works perfectly on hard reload but on normal reload it is not able to find $('.home-banner-img-container') element which is inside of carouselHeight function.

Please help me to find a solution for this. Thank you.

Tales
  • 269
  • 3
  • 14
  • You can use the function `find()` to make this happen like ` $("parent element").find(".home-banner-img-container")`. – Kunal Raut Apr 06 '20 at 10:29
  • @KunalRaut The $('.home-banner-img-container').length is 0 as window.load is working before the dom load. So even find() method will not work. – Tales Apr 06 '20 at 10:34
  • In that context, so what about waiting to load for a same element `$(".home-banner-img-container").on('load', function() { carouselHeight(); });` – Kunal Raut Apr 06 '20 at 10:45
  • $(".home-banner-img-container") element is a container which contains img tags. After load of this images. I want to call the function. The $(".home-banner-img-container") is created dynamically in ajax call – Tales Apr 06 '20 at 10:49
  • `$(".home-banner-img-container").on('load', function() { carouselHeight(); });` not working. – Tales Apr 06 '20 at 11:28

1 Answers1

1

I have found the solution on stack overflow where I have added the below code in ajax call complete method.

function imageLoaded() {
       // function to invoke for loaded image
       // decrement the counter
       counter--; 
       if( counter === 0 ) {
           // counter is 0 which means the last
           //    one loaded, so do something else
       }
    }
    var images = $('img');
    var counter = images.length;  // initialize the counter

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