52

Possible Duplicate:
jQuery 1.7 - Turning live() into on()

According to the jQuery API (http://api.jquery.com/on/) the function 'live' is deprecated, it is recommended to use 'on' instead. But when I replace 'live' with 'on' in my code, jQuery can't find later added elements anymore:

This works (but is deprecated):

$('li.bibeintrag').live('click', function(){
alert('myattribute =' + $(this).attr('myattribute'));
});

This is an example from the API for 'on':

$("#dataTable tbody tr").on("click", function(event){
    alert($(this).text());
});

When I change my code to this ('live' replaced with 'on') it does not work anymore (jQuery will not find later added elements (e.g. with append)):

$('li.bibeintrag').on('click', function(){
alert('myattribute =' + $(this).attr('myattribute'));
});

What am I doing wrong? Can someone help, please?

Community
  • 1
  • 1
CarpeTempus_
  • 712
  • 1
  • 6
  • 10
  • Here's a more detailed post with more info on this issue: http://weblog.west-wind.com/posts/2013/Jun/12/Replacing-jQuerylive-with-jQueryon – Rick Strahl Sep 26 '14 at 09:35

3 Answers3

66

You should add event to any parent element of li.bibeintrag.

$('ul').on('click', "li.bibeintrag", function(){
    alert('myattribute =' + $(this).attr('myattribute'));
});
VisioN
  • 143,310
  • 32
  • 282
  • 281
  • Great! Now it works.. thanks a lot from a jQuery-greenhorn :) – CarpeTempus_ May 15 '12 at 15:54
  • 13
    If I understand correctly, this isn't technically an exact replacement since with this approach items within a dynamically added `
      ` element will not get the 'click' handler. To exactly replicate what `live()` does using `on()`, you have to select `document` (or perhaps `body`).
    – aroth Sep 30 '13 at 23:22
37

jQuery's live, when viewed through the $.on style would have looked like this:

$(document).on("click", "li.bibeintrag", function(){

});

It would listen to click events at the document level, and determine whether their target matched the second parameter of $.on. You and I are encouraged to do this our selves, but rather than listening at the document level, we want to listen much closer to the element itself (so the event doesn't need to propagate too far before it's handled).

Since you're responding to clicks on an li, listen at the level of that items parent:

$("ul#myList").on("click", "li.bibeintrag", function(){
  /* Respond */
});

Keep in mind that without providing the second parameter of $.on, the event handler is bound to the element itself, meaning you don't get the behavior of $.live which would react to dynamically added elements.

Sampson
  • 265,109
  • 74
  • 539
  • 565
  • 3
    This should be the accepted answer, as it covers both this scenario, as well as the general case. – Aman Feb 07 '16 at 05:12
0

This should work

$('ul').on('click','li.bibeintrag' function(){
  alert('myattribute =' + $(this).attr('myattribute'));
});
Shyju
  • 214,206
  • 104
  • 411
  • 497