Jquery: fadeIn images after DOM has loaded. Works sometimes..?

倖福魔咒の 提交于 2019-12-03 16:37:00

I'm guessing it is because the images are cached, so the load never fires.

Try excluding cached images from being hidden:

$(document).ready(function(){
   $(".image_ad").not(function() {
       return this.complete;
   }).hide().bind("load", function () { $(this).fadeIn(400); });
});

or hide them, but do a fadeIn on the complete ones immediately.

$(document).ready(function(){
   $(".image_ad").hide().not(function() {
       return this.complete && $(this).fadeIn(400);
   }).bind("load", function () { $(this).fadeIn(400); });
});

I have a feeling that sometimes the dom hasn't fully loaded by the time the script has run, I know it's in a document.ready but it might be possible..

I think the problem is rather the other way around: the dom may have fully loaded after the images have. So when your load handler gets attached, the images will already have loaded and the handler is never fired.

You can work around this either by checking for image.complete or by inserting the images via js and attaching the load handler right away.

Try:

$(document).ready(function(){
    $(".image_ad").hide().bind("load", function () { $(this).fadeIn(400); }).each(function() {
        if(this.complete && jQuery(this).is(":hidden")) {
            jQuery(this).fadeIn(400);
        }
    });
});

(or something like that).

Not sure if this will help or not, but you can get rid of the hide() call by just adding this to your css:

img.image_ad{
  display: none;
}

You are better off hiding the images via css class

.image_ad { display:none; }

And then set:

$(document).ready(function(){
    $('.image_ad').fadeIn(400);
});

What this will do is make sure the images are hidden to begin with, and then once everything is received and loaded, fade the images in.

I adapted this very simple function from some code I found on another forum. It includes a callback function for you to use when the images have finished loading. Although it doesn't fade in each image as it has loaded, it fades in all the images when all the images in a stated container have finished loading. I'm sure you can adapt this code it need be.

function imgsLoaded(el,f){
  var imgs = el.find('img');
  var num_imgs = imgs.length;

  if(num_imgs > 0){
    imgs.load(function(){
      num_imgs--;
      if(num_imgs == 0) {
        if(typeof f == "function")f();//custom callback
      }
    });
  }else{
    if(typeof f == "function")f();//custom callback
  }
}

USAGE:

imgsLoaded($('#container'),function(){

$('.image_ad').fadeIn(400);

});

Hope this helps!

W.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!