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.
This is what
.live()is for 🙂 Like this:.live()doesn’t add an event handler when an element is added really, but it adds an event handler todocumentwhen you run it, and listens forclickevents that bubble up. Since old and new elements bubble the same way…it doesn’t matter when they were added, theclickhandler 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#contentcontainer via AJAX, it’d look like this:This adds that listener for bubbling events at
#contentwhich just saves a few bubbles before catching it, as opposed to having it go all the way todocument…in practice either are fine and you can’t tell the performance difference, unless you’re doing a ton of.live()event handlers.