jQuery: how to replace .live with .on?

Jquery

Jquery Problem Overview


> 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?

Jquery Solutions


Solution 1 - Jquery

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

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

Solution 2 - Jquery

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.

Solution 3 - Jquery

This should work

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCarpeTempus_View Question on Stackoverflow
Solution 1 - JqueryVisioNView Answer on Stackoverflow
Solution 2 - JquerySampsonView Answer on Stackoverflow
Solution 3 - JqueryShyjuView Answer on Stackoverflow