Adam Tomat
Adam Tomat

Reputation: 11526

jQuery IE doesn't fire load event

I'm having an issue when it comes to showing images once they've loaded. The effect I want is to show a loading .gif behind the image and when it's loaded fade it in. The following code works for any images I load in via AJAX, however on page load I'd like the same effect.

$(function() {
    $("#products img").hide().bind("load", function() {
        $(this).fadeIn(300);
    });
});

Note, this works nicely in all browsers except IE (only tested 9). From what I understand it's not firing the load event because either the image is cached or the image has loaded before the event has been binded. I want the browser to cache images so adding a date/time stamp to the end of the image src is not really an option.

Is there a way I can say If the image is already loaded in some form or another, show it. Otherwise hide it and fade it in once it's loaded. ?

Edit: I tried setting up a fiddle but it didn't really like it. Here it is anyway if it's helpful

Edit

If anyone is interested I've put up a quick js performance test for the two answers. enter image description here
(source: grabilla.com)

Upvotes: 1

Views: 427

Answers (2)

robertklep
robertklep

Reputation: 203359

You could add a filter which passes only images which haven't yet been loaded:

$("#products img")
  .filter(function(i, img) { return ! img.complete })
  .hide()
  .bind("load", function() {
    $(this).fadeIn(800);
  });

demo

Upvotes: 2

iappwebdev
iappwebdev

Reputation: 5910

I had the same problem and solved it like this:

 $("#products img").one('load.FadeIn', function () {
     $(this).fadeIn(300);
 });

 $("#products img").trigger('load.FadeIn');

Either image has already been loaded and fades in or we manually trigger the event.

Upvotes: 4

Related Questions