Consider the following three statements in my page. The elements #not_ajax_element and #ajax_element are buttons. The element #ajax_element is loaded into the page by a previous ajax call (not shown).
// #not_ajax is 'static' element. THIS WORKS
$("#not_ajax_element").on("click", "button", function() {
alert('Not ajax');
});
// #ajax_element is loaded by a previous ajax call. THIS DOES NOT WORK.
$("#ajax_element").on("click", "button", function() {
alert('Not ajax');
});
// #ajax_element is loaded by a previous ajax call. THIS WORKS.
$(document).on("click", "#ajax_element", function () {
alert('Not ajax');
});
As can be determined by the comments, the on() syntax seems to be different for static and dynamic elements.
Is this documented behaviour, or am I missing something important in the implementation.
What exactly is the #ajax_element? Is that a button or just a div container? The 2nd doesn’t work because you’re watching for a ‘click’ event for a button inside an #ajax_element. The third works because you’re listening for the ‘click’ event within the entire scope of the document.body context. You have to make sure that you’re listening in the proper context or scope, otherwise, it won’t work.