load event for images appended later to the DOM

I've read jquery: how to listen to the image loaded event of one container div?

My case is similar: I have a <body contentEditable="true"/> tag that is edited with a visual editor. The innerHTML of this body is modified by the editor and events are fired.

The problem is that I have to handle a resize logic. The current resize logic in the library is:

    this.$body.on('keyup keydown paste change focus', function() {
        return _this.adjustHeight();

This works pretty fine except the change event is not fired on drag&dropping images, but fortunatly a focus event is triggered. But when the event is fired, the image is not loaded yet so it doesn't resize to the good size.

What is the best way to listen to image loadings for images that are added to the DOM lately using Js code? I tried using $(window).load(fn) but didn't catch anything.


You could bind the adjustHeight function to the load event of image elements as they are added, like so;

this.$body.on('keyup keydown paste change focus', function() {
    $(this).find('img').off('load', _this.adjustHeight).on('load', _this.adjustHeight);
    return _this.adjustHeight();
  • $(this) is the same as this.$body (but allows you to extract the function outside it's current holder).
  • .find('img') gets all image elements within $(this) (so within the editable area)
  • .off('load', _this.adjustHeight) removes the event handler from the image element, without this you could end up binding the function several times which would also cause it to be called just as many times which could become a performance issue easily
  • .on('load', _this.adjustHeight) adds the event handler to the image element, so this gets called when the image is loaded

What comes to mind is that you might need to throttle the adjustHeight function to not be called too often to prevent it from freezing up your browser when a user drags and drops a lot of images at once (unless it isn't as expensive a function as I imagine it could be). But if this does turn out to be an issue you would probably also have to do that with other solutions.

Need Your Help

Unique key in Sphinx

database sphinx unique-constraint

Is it possible to set a unique key on the attribute in Sphinx? I mean

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.