What is jQuery .live() event handler

If you did not face with .live() handler before, this post is probably for you! It makes event handling code much cleaner and easier to use on heavily dynamic pages.

First, lets look into jQuery documentation:

Description: Attach an event handler for all elements which match the current selector, now and in the future.

Most interesting part in this sentence is the end phrase “now and in the future“.

What does it mean?

Very simple and powerful thing! It binds specified event like click to element even if it does not exists yet and would appear later.

This is very handy in AJAX applications. Lets see an example using .click event and then rewrite it using .live()

Usage scenario of .live()

Quite often in Rich UI bases on HTML and AJAX some parts of page are requested from server and inserted into DOM. For example AJAX paging, when user clicks on page number, new table with corresponding records is requested via GET method and inserted into place holder, like this:

JavaScript

1

2

3

$.get('/data/table?page=10',function(html){

$('.placeholder').html(html);

});

Now think that HTML code received from the server has a delete/edit button on each row. To handle these buttons clicks, it is needed to attach .click handles after content is inserted.

JavaScript

1

2

3

4

5

6

7

$.get('/data/table?page=10',function(html){

$('.placeholder').html(html);

// Attach event handler clicks

$('.placeholder .delete').click(function(){

// delete function

});

});

More complex UI adds more mess is in the code.

The .live() way

I rewrote example above using .live() method.

JavaScript

1

2

3

4

5

6

7

$.get('/data/table?page=10',function(html){

$('.placeholder').html(html);

});

// Attach event: it does not metter if .placeholder is loaded or not

$('.placeholder .delete').live('click',function(){

// delete function

});

Using this method no need to bother when code is loaded and inserted into HTML, you always will receive your click event.

Drawbacks

Since jQuery version 1.7 documentations says that .live() method is deprecated in favor of new .on method and here is why:

jQuery attempts to retrieve the elements specified by the selector before calling the .live() method, which may be time-consuming on large documents.

Chaining methods is not supported. For example, $(“a”).find(“.offsite, .external”).live( … ); is not valid and does not work as expected.

Since all .live() events are attached at the document element, events take the longest and slowest possible path before they are handled.

Calling event.stopPropagation() in the event handler is ineffective in stopping event handlers attached lower in the document; the event has already propagated to document.

The .live() method interacts with other event methods in ways that can be surprising, e.g., $(document).unbind(“click”) removes all click handlers attached by any call to .live()!