Using-jquery-on-event-handler-for-dynamic-elements

02-May-2013 0 Comments superuser

When we started building dynamic elements with jQuery, the issue of registering events to the dom used to be a hassle. Then .live() came to rescue where irrespective of the when the element is added to the DOM, the events associated could be triggered dynamically.
But now live() is deprecated and jQuery recommends using .on(). On() works fine everywhere and we do not even realize or even bother to find out what is the benefit of using .on() over .live() or why has jQuery  given up on the beautiful sounding “live” function.
Now suddenly if you are curious about what “on()” brings along, check out this article http://api.jquery.com/on/.
Conventionally, when we keep using .on(), this is how we will be using,
$("p").on("click", function(){
alert( $(this).text() );
});
But when it comes to working with dynamically created elements, this fails. Actually, for dynamically created elements(where the concept of event delegation comes into play), there is a slight variation of .on() method where the selector itself is considered as argument.
$(document).on("click", "p", function(){
  alert( $(this).text() );
});
Comments