I am wondering whether there are any circumstances where it would be better to use .click(function {...});
rather than .live('click', function {...});
?
From what I gather the live option seems to be a better option and I am hence using it in almost all circumstances instead of the plain .click(), especially given a lot of my code is loaded asynchronously.
EDIT: Another part to this question. If I'm asynchoronously loading all the javascript in, .click will still pickup all elements already in the dom. Right?
There might be times when you explicitly want to only assign the click handler to objects which already exist, and handle new objects differently. But more commonly, live doesn't always work. It doesn't work with chained jQuery statements such as:
$(this).children().live('click',doSomething);
It needs a selector to work properly because of the way events bubble up the DOM tree.
Edit: Someone just upvoted this, so obviously people are still looking at it. I should point out that live
and bind
are both deprecated. You can perform both with .on()
, which IMO is a much clearer syntax. To replace bind
:
$(selector).on('click', function () {
...
});
and to replace live
:
$(document).on('click', selector, function () {
...
});
Instead of using $(document)
, you can use any jQuery object which contains all the elements you're monitoring the clicks on, but the corresponding element must exist when you call it.