Home > Enterprise >  How to show div only after all the image inputs loaded?
How to show div only after all the image inputs loaded?

Time:05-14

I want the div "container" shows only after all image buttons in the div "inner" fully loaded. Or outer_1 and inner_1 show together after 1.jpg is loaded.

  <div  id="top">
     <div  id="outer_1"><div  id="inner_1"><input type="image" src="1.jpg"></div></div>
     <div  id="outer_2"><div  id="inner_2"><input type="image" src="2.jpg"></div></div>
     <div  id="outer_3"><div  id="inner_3"><input type="image" src="3.jpg"></div></div>
 </div>  

I have tried the below solution I found here but couldn't help. I am totally new in programming, may I know how can I do this?

    var $images = $('.inner input');
    var loaded_images_count = 0;

    $images.load(function(){
       loaded_images_count  ;
       if (loaded_images_count == $images.length) {
           $('.container').show();
    }
    });

CodePudding user response:

Your code is almost correct. The issue you have is that you're using the load() method, which is used to retrieve content from the server using AJAX, not the load event, which fires on img elements when they are ready to be displayed.

To fix this use on() instead of load():

var $images = $('.inner input');
var loaded_images_count = 0;

$images.on('load', function() {
  loaded_images_count  ;
  if (loaded_images_count == $images.length) {
    $('.container').show();
  }
});

CodePudding user response:

Normally, loaded doesn't mean rendered.

If you develop application on framework such as Angular, It will provided rendered event for you. In case you develop application by only pure javaScript or even with jQuery, Use setTimeOut might be help you (just in some case).

$images.load(function(){
   loaded_images_count  ;
   if (loaded_images_count == $images.length) {
       setTimeout(function(){
           $('.container').show();
       }, 0);
}
});
  • Related