hsz hsz - 1 year ago 70
jQuery Question

jQuery on() method does not bind events like live() did

As described on


As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.

Right. So instead of

$('.dynamicallyCreatedElement').live('click', function(){

I should use:

$('.dynamicallyCreatedElement').on('click', function(){

However it does not bind event to elements created after
calling. So is it really better
method ?

Am I missing something ?

Answer Source

To use on in the same manner as live used to work you need to use it like:

$(document).on("click", ".dynamicallyCreatedElement", function() {   

So you bind the on handler to the document itself (or, actually, the container element where the new wlements will be "appearing" -- Thanks to @devnull69 for the clarification), then pass it an event type and the selector.

You'll find a couple of examples halfway through the live documentation page.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download