Saturday, July 9, 2011

Running Code Unobtrusively When the DOM is Ready

The first thing you need to be up and running with jQuery is what’s called the “document ready” handler. Pretty much everything you code in jQuery will be contained inside one of these. This accomplishes two things: First, it ensures that the code does not run until the DOM is ready.

This confirms that any elements being accessed are actually in existence, so the script won’t return any errors. Second, this ensures that your code is unobtrusive. That is, it’s separated from content (XHTML) and presentation (CSS). Here is what it looks like:





Although you will normally include your jQuery code inside the above handler, for brevity the rest of the code
examples in this tutorial will not include the “ready” handler.

No comments:

Post a Comment