1

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?

maxp
  • 24,209
  • 39
  • 123
  • 201

2 Answers2

2

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
  • 339,989
  • 67
  • 413
  • 406
  • 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? – James May 17 '10 at 14:51
  • 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 May 17 '10 at 14:53
  • 1
    @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 May 17 '10 at 14:54
  • 1
    @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. – James May 17 '10 at 14:54
  • @karim79, if that's the case then okay. – James May 17 '10 at 14:55
  • @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 May 17 '10 at 14:56
1

Check the complete property of the image(s)

Josh Stodola
  • 81,538
  • 47
  • 180
  • 227