JQuery - Migrating from live () to on ()

I understand that the "live" function is now deprecated. How can I transfer the following to use the new "on"?

$('a.action').live( "click", function (evt) { // Do stuff } 

The scenario is that a.action is created on the fly. I tried this, to no avail:

 $('a.action').on( "click", function (evt) { // Do stuff } 
+7
source share
2 answers

If you want the actual performance of .live() , where a.action objects a.action not exist yet when adding an event handler, then you should find the parent DOM of all a.action elements that always exist and bind .on() to the following:

 $(parent selector).on('click', 'a.action', function (evt) { // Do stuff }); 

This parent should be as close as possible to a.action objects for maximum efficiency. For this reason, it is NOT advisable to bind to document .

In fact, one of the reasons .live() deprecated because it is attached to the document object and can easily lead to performance problems when there were too many events flowing through one object (events related to event processing were affected),

For more information, see these other related my answers:

jQuery.live () vs .on () method to add click event after loading dynamic html

How does the new on () jQuery method compare to the live () method in performance?

Should all jquery events be bound to $ (document)?

+8
source
 $(document).on('click', 'a.action', function (evt) { // Do stuff }); 
+1
source

All Articles