views:

19

answers:

1

Hi all!

Can someone please advise a good approach to this problem:

On page load, an event handler is added to a page element. For example:

// Javascript
// when page is loaded...
jQuery(document).ready(function) {
  // assign this handler to the buttonDiv element...
  jQuery("#buttonDiv").click(function() {
    // to alert "hello"
    alert("hello");
  });
}


// HTML 5
<div id="buttonDiv">Click me </div>

This works as expected - GREAT!

But suppose the div#buttonDiv wasn't present when the document is loaded and is added to the DOM later using Ajax. In this case, the click() event handler is not added and no alert will be called.

How would one add an event handler to this element without using in-line javascript?

Any suggestions welcome.

+1  A: 

This is what .live() is for :) Like this:

jQuery(function) {
  jQuery("#buttonDiv").live("click", function() {
    alert("hello");
  });
});

.live() doesn't add an event handler when an element is added really, but it adds an event handler to document when you run it, and listens for click events that bubble up. Since old and new elements bubble the same way...it doesn't matter when they were added, the click handler still works, as long as the selector matches.

There's also a similar .delegate() (which even uses .live() internally) that you can use if you know the button will be inside a certain container, say you're re-loading the #content container via AJAX, it'd look like this:

jQuery(function) {
  jQuery("#content").delegate("#buttonDiv", "click", function() {
    alert("hello");
  });
});

This adds that listener for bubbling events at #content which just saves a few bubbles before catching it, as opposed to having it go all the way to document...in practice either are fine and you can't tell the performance difference, unless you're doing a ton of .live() event handlers.

Nick Craver
Thanks Nick... That was a big help!
Gavin Morrice