Hide images on the finished document, fade in each image when loading it

I am trying to write a jquery script that disappears in Images when they load using setInterval.

My current code does not work - the "upload image" class is not deleted.

So, two questions: 1) Why is the code not working, and 2) is this the best way to accomplish what I want to do? Is there a better way?

(function($) { var $props = $('#properties'), $imgs = $props.find("img"); $imgs.addClass('image-loading'); (function updateImages() { setTimeout(function() { $imgs.each(function(){ $me = $(this); // If image is loaded, remove class $me.load(function(){ $me.removeClass('image-loading'); }); }); // if all images are loaded, stop the loop $imgs.load(function () { return false; }); updateImages(); }, 100); })(); })(jQuery); 
+4
source share
3 answers

It looks like a partial implementation. Try the following:

 (function($) { var $props = $('#properties'), $imgs = $props.find("img"), loadCounter = 0, // you init these, but never use them? nImages = $imgs.length; $imgs.addClass('image-loading'); (function updateImages() { setTimeout(function() { $imgs.one("load", function() { $(this).removeClass('image-loading'); // to manually trigger onload if image is in cache }).each(function () { if (this.complete) { $(this).trigger("load"); } }); updateImages(); }, 100); })(); })(jQuery);​ 

Demo is here.

+2
source

I have a plugin that can help you with this. Turn on the jQuery preloadImages plugin and try this code:

 properties.preloadImages(function(){ // this refers to the image that is done loading. $(this).removeClass("image-loading"); })/*.done(function(){ alert("All images are loaded!"); })*/; 

Edit to clarify:
This code will replace (function updateImages(){...})()

+1
source

I ended up using the following jQuery plugin:

https://github.com/farinspace/jquery.imgpreload

The syntax is very simple:

  var $imgs = $('#properties').find("img"); $imgs.imgpreload({ each: function() { $(this).removeClass('image-loading'); } }); 

This is much lighter weight and simpler than the code that I originally tried to crack. And he does exactly what I want him to do.

0
source

Source: https://habr.com/ru/post/1397063/


All Articles