Interview Questions

Why do my events stop working after an AJAX request?

jQuery Interview Questions and Answers


(Continued from previous question...)

Why do my events stop working after an AJAX request?

Frequently, when you've added a click (or other event) handler to all links using $('a').click(fn), you'll find that the events no longer work after you've loaded new content into a page using an AJAX request.

When you call $('a'), it returns all the links on the page at the time it was called, and .click(fn) adds your handler to only those elements. When new links are added, they are not affected. See the AJAX and Events Tutorial for a longer discussion.

You have two ways of handling this:

Using event delegation

Event delegation is a technique that exploits event bubbling to capture events on elements anywhere in the DOM.

As of jQuery 1.3, you can use the live and die methods for event delegation with a subset of event types. As of jQuery 1.4, you can use these methods (along with delegate and undelegate starting in 1.4.2) for event delegation with pretty much any event type.

For earlier versions of jQuery, take a look at the Live Query plugin by Brandon Aaron. You may also manually handle event delegation by binding to a common container and listening for events from there. For example:

$('#mydiv').click(function(e){
if( $(e.target).is('a') )
fn.call(e.target,e);
});
$('#mydiv').load('my.html');


This example will handle clicks on any element within #mydiv, even if they do not exist yet when the click handler is added.
[
Using event rebinding

This method requires you to call the bind method on new elements as they are added. For example:

$('a').click(fn);
$('#mydiv').load('my.html',function(){
$('#mydiv a').click(fn);
});


Beware! As of jQuery 1.4.2, binding the same handler to the same element multiple times will cause it to execute more than once. This differs from previous versions of jQuery as well as the DOM 2 Events spec (which normally ignores duplicate event handlers).

(Continued on next question...)

Other Interview Questions