views:

45

answers:

2

I know in jquery it is possible to call the javascript/jquery onload()/load() functions on, for example an image (<img>).

However, if in jquery if i use .html(htmlString) to insert an image after the dom has loaded, how can i add a listener to handle the images onload event? Is there a property I can check to see various images and if they have loaded?

+2  A: 

After appending your html, you can bind the load event to the contained images:

$("#foo").html(htmlString).find("img").one("load", function() {
    ...
}).each(function() {

    // image has been cached, so load event won't fire unless we explicitly call it
    if(this.complete) $(this).trigger("load");
});
karim79
Wouldn't it be better to create the image and then bind it straight away rather than having to do this kind of redundant selecting?
J-P
Make sure to do `.one('load', ` instead of `.load(` in this case. @J-P: Yes, but then you wouldn't be answering the question..
Nick Craver
@J-P - What I understood from the question is that he wants to bind `load` to images which are part of some arbitrary HTML string. @Nick - cheers, updated that in the answer.
karim79
@Nick, that's true. But it seems we should still at least mention the ideal way of doing something like this... instead of just passively answering direct questions.
J-P
@karim79, if that's the case then okay.
J-P
@J-P - What if this is content coming from an ajax request for an example? Same problem, you need to select the images and bind them. Normally I agree that there are better alternative approaches, but this question in particular is a **very** common occurrence, one in which you can't change the overall approach.
Nick Craver
+1  A: 

Check the complete property of the image(s)

Josh Stodola