jQuery: AJAX and the live() method

Have you ever noticed what happens when an AJAX content is inserted in a web document? If you try to attach some DOM events to the newly inserted content, nothing happens. In jQuery there are two solutions to this problem. First, you can attach an event to the target element when the transaction is complete, for example by using the success method of the $.ajax() wrapper. This solution works fine, but there's a catch: if you have multiple target elements, your code is actually going to become unwieldy. The second solution, instead, it's a lot neater: simply use the live() method to attach an event handler to your target element.

The live() method simply keeps track of the current status of the DOM and reacts to any change that might take place on your document. In other words, this method observes the DOM status in order to allow us to add some further behaviors to it. Let's do an example. Suppose that we have a link that fires an AJAX transaction. On the server side, the content returned is an HTML element. You want this element to show an alert when clicked. First, our file is a plain text file that contains the following line:

<div id="foo">Click me</div>

Very simple. This element has an ID, so the first thing we need to do is using the live() method to attach an event to it:

$('#foo').live('click', function() {
    alert('I am foo!');

We've just attached our event to the AJAX element. Now we can perform the actual request:

$('#run').click(function(e) {

        type: 'GET',
 url: 'live-test.txt',
 data: null,
 success: function(text) {
     $(text).insertAfter('body > p');


Once clicked, our new HTML element will alert "I am foo!". You can see this test here.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.