Skip to content Skip to sidebar Skip to footer

How To Attach Load Handler To Dynamically Created Items

I am trying to bind a load handler to a dynamically created object (backbone view in my production code). I tried to use the approach outlined in In jQuery, how to attach events to

Solution 1:

Unfortunately the usage of on with a subselector only works with event types that bubble up. The DOM load event does not bubble up the tree, so it will never reach body where you are listening for it.

See http://en.wikipedia.org/wiki/DOM_events

You will need to manually attach the handler to any images you create.

$(document).ready(function() {
  $("body img").on("load" onLoad);

  create();
});

functon onLoad(){
    console.log("foo");
}

functioncreate(){
  $("<img />")
    .on('load', onLoad)
    .attr("src", "http://www.pureweber.com/wp-content/uploads/2011/04/jquery_icon.png")
    .appendTo('body');
}

Post a Comment for "How To Attach Load Handler To Dynamically Created Items"