Alex Rivera | Logout

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

Asked 2011-11-19T01:05:15.587
179

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.

Edit
Report

1 Answer

39

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.

answered 2011-11-19T01:06:43.507

Your Answer