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

Jquery

Jquery Problem Overview


I need to add a handler for the click event of future <div> elements, that don't exist yet. Normally, I would use jQuery's .live function to handle this, but it seems that it is now deprecated in favor of .on.

To use the .on method in this manner, jQuery suggests setting the selector parameter, to allow creating a delegated event, and offers this example code:

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

That's all fine and good, but what do I put in for my intial selector, where they have #dataTable tbody? Note that $.on() doesn't work.

Jquery Solutions


Solution 1 - 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/

Solution 2 - Jquery

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.

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
QuestionBradView Question on Stackoverflow
Solution 1 - JquerywrschneiderView Answer on Stackoverflow
Solution 2 - JqueryBradView Answer on Stackoverflow