A. K. M. Tariqul Islam
A. K. M. Tariqul Islam

Reputation: 2834

Hide loading animation after image loaded

I have a jQuery script that hides the loading animation after the original image has loaded. Here is the HTML code:

<img id="loading_img" src="loading.gif">
<img id="q" style="display: none;" src="abc.png"/>

And here is the javascript:

$('#q').load(function(){
    $('#loading_img').hide();
    $('#q').show();
});

But the problem is, the loading image doesn't hide on 100% time. Sometime it stays, and the original image doesn't appear. I tried changing the positions (original image then loading image) but nothing happened. What should I do to make the code working on every time?

Upvotes: 3

Views: 2188

Answers (1)

adeneo
adeneo

Reputation: 318342

The load event won't fire on an image that is hidden in most browsers:

<img id="loading_img" src="loading.gif">
<img id="q" style="display: none;" src="abc.png"/>

You'll have to create a new image in javascript, and listen for the load event on that image :

var img = new Image();
img.onload = function() {
    document.getElementById('loading_img').style.display = 'none';
    document.getElementById('q').style.display = 'inline';
}
img.src = document.getElementById('q').src;
if (img.complete) img.onload();

or more jQuery'ish

$(new Image()).on('load', function() {
   $('#loading_img').hide();
   $('#q').show();
}).prop('src', $('#q').prop('src'))
  .each(function() { if (this.complete) $(this).trigger('load');})

Upvotes: 3

Related Questions