Alex
Alex

Reputation: 8663

Trying to replace $.live(..) with $.on(..)

I've been reading about replacing jQuery live() functions with on(), but they only work the same way as non-live functions.

For example, using the $('a').on('click', function(){}); has the same effect as using: $('a').click(function(){});

I need to replicate the functionality of $('a').live('click', function(){}); because I'm adding elements to the page dynamically.

Upvotes: 1

Views: 488

Answers (2)

gdoron
gdoron

Reputation: 150253

You need to provide a selector:

$('#container').on('click', 'a', function(){})

Where #container is the id of the static parent of all the relevant anchors.
Try to attach the on to the closest static parent.

on docs:

if selector is omitted or is null, the event handler is referred to as direct or directly-bound. The handler is called every time an event occurs on the selected elements, whether it occurs directly on the element or bubbles from a descendant (inner) element.

When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.

Upvotes: 4

jfriend00
jfriend00

Reputation: 707258

The equivalent of:

$('a').live('click', function(){});

is this:

$(document).on('click', 'a', function(){});

But, .on() is more powerful because rather than attach all event handlers to the document object like .live() does, you can pick a static parent that is much closer to your dynamic objects and will be more efficient, particularly if you have a lot of delegated event handlers.

For example if you had a container div called links, you would do this:

$("#links").on('click', 'a', function(){});

The selector in the jQuery object is the static object that you want the event handler bound to. The selector in the arguments to .on() is a selector that matches the objects who's events you want to handle that will bubble up to your static parent object.

Upvotes: 2

Related Questions