Reputation:
With the newer jQuery .click()
, .submit()
, etc. was replaced by:
$('#foo').on('click', function() {
//
});
in terms of best practice. Did anything similar happen to .live()
? Or is this still the best way to do it?
$('#foo').live('click', function() {
//
});
Upvotes: 1
Views: 77
Reputation: 22339
On() has all the abilities of all other bindings. To bind to dynamic elements you can use on()
like this:
$(document).on('click', '#foo', function() {
//
});
Preferably you want to use a close static element instead of document
.
To quote from another post of mine regarding the many binding methods jQuery has on offer:
bind()
was added in 1.0,live()
in 1.3,delegate()
in 1.4.2 andon()
in 1.7.As of 1.7
on()
is the preferred use andlive()
is deprecated and not recommended at all. If you are using 1.3 usebind()
instead oflive()
and as of 1.4.2 usedelegate()
instead oflive()
and as of 1.7 useon()
instead of any of the others.
You can see the full post here, which also list the many drawbacks of live()
and why it should not be used any more in jQuery 1.7 or later.
Upvotes: 3
Reputation: 33661
Delegation using .on()
is the correct way instead of using live
$('staticAncestorElement').on('click','#foo',function(){
});
as you can see from the jQuery live() documents
$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+
Upvotes: 3
Reputation: 22580
.click
was not replaced with .on("click"
. Read the documentation.
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.
.live
was replaced by .on
and .off
.
Other functions like .click
will continue to work as expected
Upvotes: 1
Reputation: 94121
With the newer jQuery .click(), .submit(), etc. was replaced by
They weren't replaced. click
and submit
still work but now they are shortcuts to on
. The methods that are deprecated are bind
and live
. Now you can do this to delegate events:
$(closestStaticParent).on('click', 'element', function(){ ... })
Upvotes: 1