Look at the comments first. After jQuery 1.7 on can delegate events:
"The .on () method attaches event handlers to the currently selected set of elements in the jQuery object. Starting with jQuery 1.7, the .on () method provides all the functionality needed to attach event handlers. To get help converting from old jQuery event methods see..bind () ,. delegate () and .live (). "
So, before jQuery 1.7, this is the correct answer:
At first itβs better, because the document event is ready when the HTML document is fully loaded in the DOM. And then you are sure that you have all the elements in place, and you can associate events with them.
But if you bind the event before loading the '#expandAllLessons' element in the DOM, then it simply wonβt work, because the jQuery selector will not find any elements and will not bind this event anywhere.
After 1.7, both will work almost the same. In practice, since in the first case, when you fire an event before the document is ready, it will not be executed. In the second example, it will be executed because it was attached when the script was loaded.
source share