views:

28

answers:

1

What is the appropriate method to get the already-initialized javascript to interact with content loaded using jQuery's load() method?

Example: You have a table with an onclick event for each row, then append() a new row to the table, suddenly the onclick() event does not fire.

Hopefully it is possible to do this without manually re-initializing every event by writing it into the code that executes the load().

I've looked at $.getScript, live(), and bind() - but haven't gotten any to work. Before I head into hours of trial-and-error, I'd appreciate some guidance.

A: 

For the event examples you want .live() or .delegate(), for example:

$("table").delegate("tr", "click", function() {
  //do something, the table row is this, for example:
  $(this).toggleClass("selected");
});

What this does is attach an event handler to the <table> element, which listens for events to bubble up (which elements do regardless of when they were added) and acts upon those events if the element the event came from matches the selector, in this case a <tr>.

Or it's an element with an unknown parent, use .live() like this:

$(".something").live("click", function() {
  $(this).toggleClass("selected");
});

.live() works very similarly (in face .delegate() uses .live() internally), it just attaches to document, so a parent higher in the DOM.

Nick Craver