user967451
user967451

Reputation:

Is there a better way to attach events to AJAX loaded elements than to use .live()?

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

Answers (4)

Nope
Nope

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 and on() in 1.7.

As of 1.7 on() is the preferred use and live() is deprecated and not recommended at all. If you are using 1.3 use bind() instead of live() and as of 1.4.2 use delegate() instead of live() and as of 1.7 use on() 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

wirey00
wirey00

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

SpYk3HH
SpYk3HH

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

elclanrs
elclanrs

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

Related Questions