.live()
has been removed in version 1.9 onwards.That means if you are upgrading from version 1.8 and earlier, you will notice things breaking if you do not follow the migration guide below. You must not simply replace .live()
with .on()
!
For quick/hot fixes on a live site, do not just replace the keyword live
with on
,
as the parameters are different!
.live(events, function)
should map to:
.on(eventType, selector, function)
The (child) selector is very important! If you do not need to use this for any reason, set it to null
.
before:
$('#mainmenu a').live('click', function)
after, you move the child element (a
) to the .on()
selector:
$('#mainmenu').on('click', 'a', function)
before:
$('.myButton').live('click', function)
after, you move the element (.myButton
) to the .on()
selector, and find the nearest parent element (preferably with an ID):
$('#parentElement').on('click', '.myButton', function)
If you do not know what to put as the parent, body
always works:
$('body').on('click', '.myButton', function)
You can avoid refactoring your code by including the following JavaScript code
jQuery.fn.extend({
live: function (event, callback) {
if (this.selector) {
jQuery(document).on(event, this.selector, callback);
}
return this;
}
});
Forward port of .live()
for jQuery >= 1.9
Avoids refactoring JS dependencies on .live()
Uses optimized DOM selector context
/**
* Forward port jQuery.live()
* Wrapper for newer jQuery.on()
* Uses optimized selector context
* Only add if live() not already existing.
*/
if (typeof jQuery.fn.live == 'undefined' || !(jQuery.isFunction(jQuery.fn.live))) {
jQuery.fn.extend({
live: function (event, callback) {
if (this.selector) {
jQuery(document).on(event, this.selector, callback);
}
}
});
}
The jQuery API documentation lists live()
as deprecated as of version 1.7 and removed as of version 1.9: link.
version deprecated: 1.7, removed: 1.9
Furthermore it states:
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live()
.live() was deprecated and has now been removed from jQuery 1.9 You should use .on()
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