4

Possible Duplicate:
jQuery callback on image load (even when the image is cached)

I have a #mainImg img with a property of opacity:0;.

When the page loads, I trigger the following jQuery code :

$("#mainImg img").load(function(){ 
   $("#mainImg img").center(); // center everything
   $("#mainImg img").animate({"opacity": "1"}, "400"); // fade the image in
});

It works il firefox/chrome/safari. I use the .load() method because in webkit browsers, the width and height are set after the image is loaded.

But when I try to load another image when I click on a thumbnail, the image doesn't work in safari (and works in chrome and firefox).

Here is my code for the thumbnail system :

$("#th2").click(function() {
    $("#mainImg").html('<img src="' + new_th2_link + '" />');
    $("#mainImg img").load(function(){ 
        $("#mainImg img").center();
        $("#mainImg img").animate({"opacity": "1"}, "400");
    });
});

In Safari the #mainImg img has a property of width:0; height:0;. Is Safari too fast ?

Community
  • 1
  • 1
onimojo
  • 578
  • 1
  • 5
  • 16
  • 1
    Unrelated to your question but you may want to save a reference to the `$('#mainImg')` or `$('#mainImg img')` or else chain your methods since you are using it so much. – Jeff Dec 19 '12 at 16:11
  • The [jQuery docs](http://api.jquery.com/load-event/) warn about problems with using `.load` on images. See [this question](http://stackoverflow.com/questions/3877027/jquery-callback-on-image-load-even-when-the-image-is-cached) for solutions. – Blazemonger Dec 19 '12 at 16:15
  • I've tried doing the `$("img").one('load', function() { // do stuff }).each(function() { if(this.complete) $(this).load(); });` fix, but it doesn't work in Safari. – onimojo Dec 19 '12 at 16:21

1 Answers1

0

Here is the solution I ended up using :

$("#mainImg img").animate({"opacity": "1"}, "400");
    setTimeout(function(){
        $("#mainImg img").center()
    }, 10);

Works in Firefox/Chrome/Safari.

onimojo
  • 578
  • 1
  • 5
  • 16