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?
There are numerous drawbacks to .live()
, such that I'd restrict its use to when:
.live()
works by attaching an event handler to document
, and checking if event.target
matches the given selector. This results in:
#some_id
are clicked.stopPropagation()
of the event since it has already reached the root (although you can still preventDefault()
).#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..triggerHandler()
on the element.