Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .on function for future elements, as .live is deprecated [duplicate]

Tags:

jquery

jQuery's documentation shows you would replace

$(selector).live(event, handler) 

with

$(document).on(event, selector, handler)

Also you have the option to be more precise and replace $(document) with a selector for a static parent of the element. For example, if you have a static table element and tr elements are added dynamically to the DOM, you could do something like $('table#id').on('click', 'tr', ...)

http://api.jquery.com/live/


I just figured it out as soon as I posted this question... Sorry about that!

The initial selector can be any parent element. Since my elements will be direct children of the body, I can use body for the selector:

$('body').on('click', '.my_class', function(event) { ...

This works because the events are going to bubble up. This is essentially normal bubbling with an extra filter of .my_class.