I see there's a new method .on()
in jQuery 1.7 that replaces the .live()
in earlier versions.
I'm interested to know the difference between them and what the benefits are of using this new method.
on() method: This method attaches events not only to existing elements but also for the ones appended in the future as well. The difference here between on() and live() function is that on() method is still supported and uses a different syntax pattern, unlike the above two methods.
In short: . bind() will only apply to the items you currently have selected in your jQuery object. . live() will apply to all current matching elements, as well as any you might add in the future. The underlying difference between them is that live() makes use of event bubbling.
Definition and Usage The live() method attaches one or more event handlers for selected elements, and specifies a function to run when the events occur. Event handlers attached using the live() method will work for both current and FUTURE elements matching the selector (like a new element created by a script).
jQuery makes it straightforward to set up event-driven responses on page elements. These events are often triggered by the end user's interaction with the page, such as when text is entered into a form element or the mouse pointer is moved.
It's pretty clear in the docs why you wouldn't want to use live. Also as mentioned by Felix, .on
is a more streamline way of attaching events.
Use of the .live() method is no longer recommended since later versions of jQuery offer better methods that do not have its drawbacks. In particular, the following issues arise with the use of .live():
- jQuery attempts to retrieve the elements specified by the selector before calling the
.live()
method, which may be time-consuming on large documents.- Chaining methods is not supported. For example,
$("a").find(".offsite, .external").live( ... );
is not valid and does not work as expected.- Since all
.live()
events are attached at thedocument
element, events take the longest and slowest possible path before they are handled.- Calling
event.stopPropagation()
in the event handler is ineffective in stopping event handlers attached lower in the document; the event has already propagated todocument
.- The
.live()
method interacts with other event methods in ways that can be surprising, e.g.,$(document).unbind("click")
removes all click handlers attached by any call to.live()
!
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