1

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.

1
  • 3
    Probably .ui-accordion-header doesn't exist when you run this Commented Aug 19, 2014 at 18:20

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm creating the elements inside the .ui-accordion-header div by importing data from JSON via Backbone JS.
You're going to want to wait until the data is loaded and the corresponding dom is created before attaching the jquery listener you have there. Try adding it in the success function of a Backbone fetch.
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.