Reputation: 11104
I'm trying to write a Jquery script that fades in Images as they are loaded, by using setInterval.
My current code is not working-- the "image-loading" class is not getting removed.
So two questions: 1) Why isn't the code 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);
Upvotes: 4
Views: 735
Reputation: 11104
I ended up using the following jQuery plugin:
https://github.com/farinspace/jquery.imgpreload
The syntax is super easy:
var $imgs = $('#properties').find("img");
$imgs.imgpreload({
each: function() {
$(this).removeClass('image-loading');
}
});
It's alot lighter weight and more straightforward than the code I had originally tried to hack together. And it does exactly what I want it to do.
Upvotes: 0
Reputation: 342635
That looks like a partial implementation. Try this:
(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);
Upvotes: 2
Reputation: 95022
I have a plugin that may help you with this. Include the jQuery preloadImages plugin and then 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 for Clarification:
This code would replace (function updateImages(){...})()
Upvotes: 1