Reputation: 26567
I have inserted this script in a webpage with 50 small images ( from 16x16px to 50x50px ):
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('img').css('opacity', '0.0').load(function(){
$(this).animate({'opacity': '1.0'});
});
});
</script>
The problem is that not every images are loaded and some doesn't appears.
Why ?
Upvotes: 3
Views: 111
Reputation: 13461
There are chances that some images are being loaded from cache. And if the image is loaded from cach then load
event would fire before dom ready
event. One way to do this would be
$('img').css('opacity', '0.0').one('load',function(){
$(this).animate({'opacity': '1.0'});
}).each(function() {
if(this.complete) $(this).load();
});
This will loop through the images and check if they has been loaded from cache, if so then it will fire load event for those images.
And I am using $.one to run the event handler only one time as we dont need it to be executed more than one time.
UPDATE:
if(this.complete)
will check if the image is already loaded(in case of cached they are) and if they are then it will fire load
event for those immediately.
And which are not loaded from cache, browser will fire load
event for them after they are loaded.
So the above code will cover all images, cached or not.
Upvotes: 3
Reputation: 2534
you can better set the opacity for images in css like
img {
opacity:0
}
and then use your code
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('img').load(function(){
$(this).animate({'opacity': '1.0'});
});
});
</script>
Upvotes: 0
Reputation: 3008
Set the default opacity
value within CSS style, not via javascript. After that, use animate
.
<style>
img { opacity:0 }
</style>
<script type="text/javascript">
$(document).ready(function(){
$('img').load(function(){
$(this).animate({'opacity': '1.0'});
});
});
</script>
Upvotes: 1
Reputation: 4431
use Preload Images javascript code...
<script type="text/javascript">
if (document.images) {
img1 = new Image();
img1.src = "image.jpg";
img2 = new Image();
img2.src = "image2.jpg";
}
</script>
and now all images preload into client machine and visible always....
OR
Flexible Array
function preload(images) {
if (document.images) {
var i = 0;
var imageArray = new Array();
imageArray = images.split(',');
var imageObj = new Image();
for(i=0; i<=imageArray.length-1; i++) {
//document.write('<img src="' + imageArray[i] + '" />');// Write to page (uncomment to check images)
imageObj.src=images[i];
}
}
}
Upvotes: 0
Reputation: 43168
Some images might already be loaded when you set their opacity to 0, thus their onload
handler has already run and you don't get the chance to make them visible again.
Upvotes: 4