Reputation: 65
Why this code doesn't work?
jQuery(".ui-accordion-header").on("click", function(event){ ... }
And this one works?
jQuery(document).on("click", ".ui-accordion-header", function(event){ ... }
Thank you.
Upvotes: 1
Views: 88
Reputation: 1677
When you have call like jQuery(".ui-accordion-header")
, jQuery assigns that method to all the objects that exist as it's loaded (when the page is loaded). So if an object with a class name ui-accordion-header
isn't a DOM element when the page is set-up, the method won't be assigned to it.
jQuery(document)
will assign it to the document, which will respond whenever a .ui-accordion-header
is clicked. Basically, if it's a DOM object that will be created sometime after the page is loaded, stick to jQuery(document)
methods. By the way, why don't you use $
? For instance, $(document)
, $(".ui-accordion-header")
, etc.
Upvotes: 1
Reputation: 4465
The first line only works if the .ui-accordion-header
already exists in the dom. Sometimes the elements are dynamically created and inserted into the dom. In such scenarios, the listeners are not bound to the newly created elements.
The reason the second way works is because the listener is tied at the document
level. So whenever any new changes are made inside the document, the listener is still bound.
Upvotes: 2