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
}
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)?
$(document).on('click', 'a.action', function (evt) {
// Do stuff
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With