crafter
crafter

Reputation: 6296

Jquery difference between $(document).on() and $(element).on for ajax and non-ajax

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.

Upvotes: 0

Views: 153

Answers (2)

Dennis Rongo
Dennis Rongo

Reputation: 4611

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.

Upvotes: 1

Kevin B
Kevin B

Reputation: 95022

The context element (the one you select and call .on on) must exist when the code is ran. That's the easy rule to go by. The behavior you are seeing is expected and documented. document always exists, and your dynamic element doesn't always exist.

Your second sample should work providing you are properly placing that code in the success callback of the ajax call because at that point (inside the success callback) the ajax added element has been added, meaning you can select it and use it as a context.

Upvotes: 3

Related Questions