A little late to the party but I thought I would try to clear up some common misconceptions in jQuery event handlers. As of jQuery 1.7, .on()
should be used instead of the deprecated .live()
, to delegate event handlers to elements that are dynamically created at any point after the event handler is assigned.
That said, it is not a simple of switching live
for on
because the syntax is slightly different:
New method (example 1):
$(document).on('click', '#someting', function(){
});
Deprecated method (example 2):
$('#something').live(function(){
});
As shown above, there is a difference. The twist is .on()
can actually be called similar to .live()
, by passing the selector to the jQuery function itself:
Example 3:
$('#something').on('click', function(){
});
However, without using $(document)
as in example 1, example 3 will not work for dynamically created elements. The example 3 is absolutely fine if you don't need the dynamic delegation.
Should $(document).on() be used for everything?
It will work but if you don't need the dynamic delegation, it would be more appropriate to use example 3 because example 1 requires slightly more work from the browser. There won't be any real impact on performance but it makes sense to use the most appropriate method for your use.
Should .on() be used instead of .click() if no dynamic delegation is needed?
Not necessarily. The following is just a shortcut for example 3:
$('#something').click(function(){
});
The above is perfectly valid and so it's really a matter of personal preference as to which method is used when no dynamic delegation is required.
References:
- jQuery docs for .on()
- jQuery docs for .click()
- jQuery docs for .live()