Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Migrating from live() to on()

Tags:

jquery

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

$('a.action').live( "click", function (evt) {

        // Do stuff 

}

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

$('a.action').on( "click", function (evt) {

        // Do stuff 

}
like image 738
Jonathan Wold Avatar asked Nov 22 '12 00:11

Jonathan Wold


2 Answers

If you want the actual .live() - type performance where a.action objects don't have to exist yet when you add the event handler, then you should find a parent DOM object of all a.action elementss that always exists and bind .on() to that like this:

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

That parent should be as close to the a.action objects as possible for maximum efficiency. For that reason, it is NOT desirable to bind to document.

In fact, one reason .live() has been deprecated is because it was bound to the document object and could easily lead to performance problems when there were too many events all flowing through the one object (event dispatching performance suffered).

See these other related answers of mine for more info:

jQuery .live() vs .on() method for adding a click event after loading dynamic html

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

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

like image 176
jfriend00 Avatar answered Oct 18 '22 02:10

jfriend00


$(document).on('click', 'a.action', function (evt) {
    // Do stuff
});
like image 22
kendaleiv Avatar answered Oct 18 '22 03:10

kendaleiv