Since jQuery live is marked as deprecated. I thought it’d be a good thing to switch to use jQuery on.
I was at first shocked to find out that “ON” did not work like “LIVE”. Without digging very far, I simply switched my old syntax that had
$('a.delete').live('click', function() {});
to
$('a.delete').on('click', function() {});
It worked for non dynamically generated DOM tree but failed to work on anything that’s dynamically generated. Thank you to stackoverflow, I was able to use the correct syntax for any bubbling event binding to
$(document).on('click', 'a.delete', function(event) {});
Here’s my jsFiddle example to better demonstrate what I’m talking about -> jQuery ON syntax vs. LIVE syntax.
Basically you can bind the .on event to any DOM element that will eventually hold the dynamically generated child element, so you could also use
$(‘#fancy_holder’).on(‘click’, ‘a.delete’, function(event) {});
or
$(‘body’).on(‘click’, ‘a.delete’, function(event) {});
Targeting the parent element can be usefull in situation in which you would prefer to use the same class names for different purposes, for example instead of having
$(document).on(‘click’, ‘a.delete_product’, function(event) {});
And
$(document).on(‘click’, ‘a.delete_client’, function(event) {});
You could have
$(‘#products_div’).on(‘click’, ‘a.delete’, function(event) {});
And
$(‘#clients_div’).on(‘click’, ‘a.delete’, function(event) {});
Again this is just an example, real life coding can bring out different opportunities to further take advantage of the .on jquery awesomeness.