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()
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:
$.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.
$.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.
I rewrote example above using .live() method.
$.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.
Since jQuery version 1.7 documentations says that .live() method is deprecated in favor of new .on method and here is why:
//Old syntax
$(selector).live(events, data, handler); // jQuery 1.3+
//New syntax
$(document).on(events, selector, data, handler); // jQuery 1.7+