jquery click(), live() and on()
Adam’s Question:
just interested to know which of – Click(), Live() and On()
is currently the preferred method to catch a user mouse click?
I assume live()
is out as this I believe scans to much of the DOM.
thankyou
From jquery docs:
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(). This method provides a means to
attach delegated event handlers to the document element of a page,
which simplifies the use of event handlers when content is dynamically
added to a page. See the discussion of direct versus delegated events
in the .on() method for more information.The .on() method attaches event handlers to the currently selected set
of elements in the jQuery object. As of jQuery 1.7, the .on() method
provides all functionality required for attaching event handlers.
For earlier versions, the .bind() method is used for attaching an event handler directly to elements.
TLDR: Always use on()
, never use live()
live()
and .bind()
methods are deprecated. live()
has also been removed where as other two are two totally two different types of event handlers.
-
.click()
is a standard event handler.click(function() { //Applies to DOM already present });
-
.on()
is used when you require event delegation. This replaced traditionalbind()
anddelegate()
.on('click', function() { //Delegates to each element is DOM as it manipulated or generated });