I’d like a jQuery expert in their own words to explain why the $(document) identifier is recommended by others for jQuery’s on() statement vs just using an element itself
Example 1: Why is using $(document) here better then Example #2?
$(document).on("click", ".areaCodeList a", function(){
// do stuff
});
Example 2: Why is using the element this way considering not good practice compared to Example 1?
$(".areaCodeList a").on("click", function(){
// do stuff
});
Both of those are valid.
The former works for dynamically added elements. You use
documentbecause you’re delegating events on children of the document object, so events bubble up to the document level. It’s also more convenient to select the closest parent you can (and the parent must exist on the page at load).The latter still works, and is a preferred way to simply bind events to specific elements.
I personally don’t recommend delegating through the
documentobject, but rather the closest parent that exists on page load.Here are the docs for
on().