Pwnna
Pwnna

Reputation: 9538

make sure an image is loaded while dynamically changing jquery

I'm changing the image src of an image node. I want to be able to make sure that it's changed before executing somecode. How would i do that?

right now i have

function changePic(imgNode, newPic, desc){
    var descNode = $("#description");
    $(imgnode).fadeTo(500, 0, function(){
        $(imgnode).attr("src", newPic);
        $(imgnode).attr("alt", desc)
        descNode.text(desc);
        $(imgnode).fadeTo(500, 1);
    });
}

Works great if the server's fast/ a local server. Works terribly if the server's slow, where the image will fade back in before changing...

any idea?

Edit: I'm loading the image when changePic is called. Any better ways to do it?

More: Also why is it not a good idea to put the last line,

$(imgnode).fadeTo(500, 1);

, outside of the callback function?

Upvotes: 1

Views: 1221

Answers (3)

Peter Örneholm
Peter Örneholm

Reputation: 2858

Preload the image, but to be sure it's completely loaded, use the .load() event.

Quote:

The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.

And don't miss this line:

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 use a special load event that fires immediately if the image is ready. event.special.load is currently available as a plugin.

I put together an example of how I think you want it to work. I switch between three images I found through Google Images. I bind the load event before I change the src of the image to be sure it's triggered. http://jsfiddle.net/xdjjR/1/

Upvotes: 2

dmitko
dmitko

Reputation: 2657

I guess, you can preload image in hidden elements, so that it's loaded with other html. When the source changed such image should be shown immediately.

Upvotes: 1

Iznogood
Iznogood

Reputation: 12843

Use the callback param doc ex from doc:

$('#clickme').click(function() {
 $('#book').fadeOut('slow', function() {
    // Animation complete.
  });
});

Upvotes: 0

Related Questions