-6

I was wandering what is the difference between 'on' and 'live'

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

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

When does it make sense to use one over the other.

Filix Mogilevsky
  • 638
  • 6
  • 12
  • Duplicate of http://stackoverflow.com/a/11686543/297641 – Selvakumar Arumugam Aug 16 '13 at 18:57
  • `live()` is deprecated in 1.7+, you can't use it at all in 1.9+. In versions before 1.7, you should use `delegate()` instead of live anyway. read - http://api.jquery.com/live/ – Dallas Aug 16 '13 at 18:58
  • Functionally `$('selector').on('click', function(){ }); == .bind` and `$(container).on('click', 'selector', function(){ }); == .live` – Selvakumar Arumugam Aug 16 '13 at 18:58
  • That's a better duplicate: [What is the difference between .click(…) and .live('click', …)?](http://stackoverflow.com/q/3651259/218196). `.on('click', ...)` is equivalent to `.click`in this case. – Felix Kling Aug 16 '13 at 19:13
  • didnt realize this was asked before. sorry for the stupid question. – Filix Mogilevsky Aug 16 '13 at 19:14
  • IMO the question that is now linked as duplicate is not a fitting duplicate, since it mostly describes why `.live` was deprecated. However, the one I linked to describes the same as me in my answer. – Felix Kling Aug 16 '13 at 19:18

1 Answers1

0
$('selector').on('click', function(){ });

will bind a click event handler to all elements selected by selector. Those element must exist at the time the call is made.

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

will bind an event handler to the document and will catch all click events on elements that match selector. Those elements don't have to exist at the time the call is made. This is also called event delegation.

You can (and should, since .live was removed in jQuery 1.9) also use .on for event delegation, but the syntax is slightly different. The equivalent to the .live call would be:

$(document).on('click', 'selector', function(){ });
Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072