I was wandering what is the difference between 'on' and 'live'
$('selector').on('click', function(){
});
$('selector').live('click', function(){
});
When does it make sense to use one over the other.
I was wandering what is the difference between 'on' and 'live'
$('selector').on('click', function(){
});
$('selector').live('click', function(){
});
When does it make sense to use one over the other.
$('selector').on('click', function(){ });
will bind a click event handler to all elements selected by selector
. Those element must exist at the time the call is made.
$('selector').live('click', function(){ });
will bind an event handler to the document
and will catch all click events on elements that match selector
. Those elements don't have to exist at the time the call is made. This is also called event delegation.
You can (and should, since .live
was removed in jQuery 1.9) also use .on
for event delegation, but the syntax is slightly different. The equivalent to the .live
call would be:
$(document).on('click', 'selector', function(){ });