1

I change some methods from $(selector).live('click', function(){}); to $(selector).on('click', function(){}); .

At first it seems to work exactly the same. But when I insert new html on the DOM, the new elements inserted with the same selector, they aren't catch by $(selector).on('click', function(){}); and before they were catch by the live() method.

why? I'm missing something?

elranu
  • 2,292
  • 6
  • 31
  • 55
  • Possible duplicate of http://stackoverflow.com/questions/8021436/jquery-1-7-turning-live-into-on – Selvakumar Arumugam Mar 28 '12 at 17:42
  • Double check what you are using for a selector. You can test by changing it to `document`. If it works with `document`, then your selector is wrong. – Brad Mar 28 '12 at 17:43
  • *"I'm missing something?"* Probably just a good reading of the documentation. –  Mar 28 '12 at 18:04

1 Answers1

4

.on takes a different set of parameters compared to .live. You can't just replace one with the other (and $(selector).on.live doesn't make sense).

The correct syntax is:

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

This will bind to all elements that match selector no matter when they are added to the DOM.

Note:

Instead of document, you can use a parent of the element(s), as long as that parent stays in the DOM.

For example:

<div id="myDiv">
    <p>Hello World</p>
    <p>Hello World</p>
</div>

Then you can do:

$('#myDiv').on('click', 'p', function(){});

That click event will fire for all <p> tags added to #myDiv.

Note:

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

is the same as doing

$(selector).bind('click', function(){})

(jQuery 1.7.1 suggests using .on instead of .bind)

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • It may be counter productive to attach it to document, no ? Any element which won't change would prevent the event from bubbling to the top ? Or am I mistaken ? – mddw Mar 28 '12 at 17:45
  • @mdi: You can attach the event to any parent of the element you want, as long as that parent stays in the DOM. I'm not too sure how bubbling works with delegated events. – gen_Eric Mar 28 '12 at 17:51
  • @mdi: The event bubbles up to the elements that `on` was called on (which then runs the delegated event), and then continues up to the `document`. http://jsfiddle.net/GdjPT/1/ – gen_Eric Mar 28 '12 at 17:57
  • @Rocket sorry I didnt write it correctly. It was just $(selector).on('click', function(){}); But reading your answer, I realize that the selector should be at the second parameter. I will try it. – elranu Mar 28 '12 at 18:04
  • @elranu: Adding a selector as the 2nd parameter to `.on`, makes the event "live"; without it, it's like doing `.bind`. – gen_Eric Mar 28 '12 at 18:06