Why should $.click() be enclosed within $(document).ready()?

The How jQuery Works document uses the example of binding a .click() inside of $(document).ready() to be certain that the element to which the .click() event is bound has been created when the function executes.

The .click() called with a function as its parameter does not execute the .click() on the nodes matching its preceding selector, but rather binds the function to the matching nodes’ onclick.

If you were to attempt to do something like this:

$('a').click(function(){
  alert('clicked me');
});

…in the document <head> or before any <a> element had been rendered, the event would not get bound to any node since no node matching the $('a') selector existed at the time the function executed.

Furthermore, if you did it when some <a> tags had been created, only those already created would get the bound event. <a> tags created after the function was bound wouldn’t have the .click() binding.

So in jQuery (and other JavaScript frameworks), you’ll often see the convention of adding event handlers, binding widgets, etc, inside a $(document).ready(function(){});

Leave a Comment