Search code examples
jqueryeventslive

Should I be using .live(...)?


When I use jQuery to attach events to elements, I typically do it like this:

$(document).ready(function() {
    $('#some_id').click(function() {
        // Do some stuff
    });
});

However, I've seen a number of examples that do it like so:

$('#some_id').live('click', function() {
    // Do some stuff
});

(Almost always without the ready wrapper.)

Is there a drawback to one way or the other, if the elements are already in the page and aren't going anywhere?


Solution

  • There are numerous drawbacks to .live(), such that I'd restrict its use to when:

    1. a large number of elements need to be bound to the same event handler, or
    2. elements are frequently added or removed.

    .live() works by attaching an event handler to document, and checking if event.target matches the given selector. This results in:

    • unnecessary checks against the selector when elements other than #some_id are clicked.
    • no opportunity to stopPropagation() of the event since it has already reached the root (although you can still preventDefault()).
    • similarly, click handlers attached to parents of #some_id (via .click() or .bind()) that return false or stopPropagation() will silence handlers attached via .live(), as the event will no longer reach the root.
    • it can only be used with a selector (string).
    • unexpected event handling order can result since events will be fired in the order they are bound, and not in bubbling order (child to parent).
    • the event is not removed if the element is removed.
    • while rare, you cannot .triggerHandler() on the element.