Live Event Handlers

If you are modifying the DOM on the fly, then you have probably noticed that any event handlers you attach don't work on elements added after page load. Let's say you are making an ajax request and your server is returning an html response that you replace a portion of your DOM with. All the normal event handlers that were applied at page load were not applied to these elements, since they didn't exist at that time, and so now you have a bunch of stuff on the screen that doesn't work. Your first thought might be to re-add all the event handlers after the DOM update is complete. This would get the job done, but wouldn't be very efficient and would require the event attachment code to be in multiple places. A better approach would be to use the "live" function introduced in jQuery 1.3 (or the livequery plugin if you are still on 1.2). Instead of applying directly to the element, it captures bubbled events and checks the target element to see if it matches what is being watched. That way, an event on any element that matches the live's selector will have the event fired. The call is basically the same, except you pass in the name type of event to watch for. [js]$("a.link_to_watch").live('click', function() {});[/js]At the time of writing this post, the event types not supported are blur, focus, mouseover, mouseleave, change, and submit. If you need to attach to those types of events, you will need to use the livequery plugin instead.