I was under the impression that jQuery's on
event handler was meant to be able to 'listen' for dynamically created elements AND that it was supposed to replace the behavior of live
. However, what I have experienced is that using on
is not capturing the click event whereas using live
is succeeding!
The tricky aspect of my situation is that I am not only dynamically creating content but I'm doing it via an AJAX .get()
call, and inserting the resultant HTML into a modal .dialog()
jQueryUI popup.
Here is a simplified version of what I was trying to accomplish (wrapped in $(document).ready(...)
):
$.get("getUserDataAjax.php", queryString, function(formToDisplay) {
$("#dialog").dialog({
autoOpen: true,
modal: true,
buttons...
}).html(formToDisplay);
});
$(".classThatExistsInFormToDisplay").on("click", function() {
alert("This doesn't get called");
});
From the documentation for on
I found this which which was how I was approaching writing my on
event:
$("p").on("click", function(){
alert( $(this).text() );
});
However, for some reason, live
will work as I expect -- whereas on
is failing me.
This isn't a question for "how can I make it work" because I have found that on
will succeed (capture clicks) if I declare it inside the function(formToDisplay)
callback.
My question is: what is wrong with on
that it isn't finding my dynamically created elements within a modal popup? My jQuery instance is jquery-1.7.2. jQueryUI is 1.8.21.
Here are two jsFiddles that approximate the issue. Click the word "Test" in both instances to see the different behavior. The only difference in code is replacing on
for live
.
Where the click is captured by live
.
Where the click is NOT captured by on
(click 'Test - click me' to see nothing happen).
I realize I may just be using on
inappropriately or asking it to do something that was not intended but I want to know why it is not working (but if you have something terribly clever, feel free to share). Thanks for your wisdom!
Update / Answer / Solution:
According to user 'undefined', the difference is that on
is not delegated all the way from the top of the document
object whereas live
does/is.
As Claudio mentions, there are portions of the on
documentation that reference dynamically created elements and that what you include in the $("")
part of the query needs to exist at runtime.
Here is my new solution: Capture click events on
my modal dialog, which, although it does not have any content when the event is created at runtime, will be able to find my content and element with special class that gets generated later.
$("#dialog").on("click", ".classThatExistsInFormToDisplay", function() {
... //(success! Event captured)
});
Thanks so much!