Does jQuery.on() work for elements that are added after the event handler is created?
Solution 1:
.on()
works with dynamically created elements if it is used properly. The jQuery doc does a pretty good job of describing it.
The way to use it for dynamic elements is to use this form:
$("static selector").on('click', "dynamic selector", fn);
The static selector must resolve to some object that is both an ancestor of your dynamic objects and is static - is present when you run this line of code and won't be removed or recreated.
The dynamic selector is a selector that matches your dynamic elements. They do not have to exist at the time the event handler is first installed and they can come and go as often as you want.
So, if "#container"
matches a static ancestor and ".foo"
matches your dynamic elements that you want click handlers on, you would use this;
$("#container").on("click", ".foo", fn);
If you really want to understand it, this is how the delegated event handling of .on()
works. When you make the .on()
call above, it attached a click event handler to the #container
object. Sometime later when you click on a .foo
object, there is no click handler on the actual .foo
object so the click bubbles up the ancestor chain. When the click gets to the #container
object, there is a click handler and jQuery looks at that handler and sees that this handler is only for objects where the original clicked-upon object matches the selector ".foo"
. It tests the event target to see if it does match that selector and if so, it calls the event handler for it.
The (now deprecated) .live()
method worked by attaching all event handlers to the document object. Since the document object is an ancestor of every object in the document, they got delegated event handling that way. So, in the example above, these two are equivalent:
$(document).on("click", ".foo", fn);
$(".foo").live("click", fn);
But, attaching all delegated event handlers on the document sometimes created a serious performance bottleneck so jQuery decided that was a bad way to do it and it was better to require the developer to specify a static ancestor that was hopefully closer to the actual target object than the document object.
Solution 2:
I think you face similar situation that i faced. this is quite a good solution for binding events withe elements generated later.
Binding Jquery Events On Elements Generated Through Other Events