Dan Tang
Dan Tang

Reputation: 1343

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 dynamic html elements?, and it works for a click handler but not a load handler. Does anyone know how to solve this?

This works (with click handler)

  $(document).ready(function() {
    $("body").on("click", "img", function(){
      console.log("foo");
    });

    create();
  });

  function create(){
    $img = $("<img />").attr("src", "http://www.pureweber.com/wp-content/uploads/2011/04/jquery_icon.png");
    $("body").append($img);
  }

But this doesn't (with load handler)

  $(document).ready(function() {
    $("body").on("load", "img", function(){
      console.log("foo");
    });

    create();
  });

  function create(){
    $img = $("<img />").attr("src", "http://www.pureweber.com/wp-content/uploads/2011/04/jquery_icon.png");
    $("body").append($img);
  }

Upvotes: 0

Views: 616

Answers (1)

loganfsmyth
loganfsmyth

Reputation: 161627

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");
}

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

Upvotes: 2

Related Questions