I have a page full of images and I want each of them to fade in when loaded. I have the following code which works but seems buggy, basically sometimes not all the image fad
It is possible that the load event will not be triggered if the image is loaded from the browser cache. To account for this possibility, we can test the value of the image's .complete property.
$(document).ready(function() {
$('img').hide();
$('img').each(function(i) {
if (this.complete) {
$(this).fadeIn();
} else {
$(this).load(function() {
$(this).fadeIn();
});
}
});
});
I use the cool script of David DeSandro to check if images have loaded.
(e.g. you can write a function which adds a class to the loaded images, so they will fade in using css transition. check it out:
http://desandro.github.io/imagesloaded/
You could take all the images and put them into one image and fade that in, but then they all come in at the same time, and it will be a big file. It depends what you want to use it for.
To deal with cached images, bobince's solution works, but as he said, it's quite ugly.
Another solution would be to hide your images in css and use the following javascript:
$(window).load(function(){
$('.contentwrap img').not(':visible').fadeIn(1000);
});
function showImages() {
$('.contentwrap img').load(function () {
$(this).fadeIn(1000);
});
});
showImages();
This way, most images are loaded properly, and if they were cached, and hidden right away (the load function not having time to be fired), the page's load event will make them appear. The page's load event ensures that everything was loaded.
I just answered this over at this thread: jQuery How do you get an image to fade in on load?
Works for me!