Introducing $(document).ready()
This is the first thing to learn about jQuery: If you want an event to work on your page, you should call it inside the $(document).ready()
function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded.
The $(document).ready()
function has a ton of advantages over other ways of getting events to work. First of all, you don't have to put any "behavioral" markup in the HTML. You can separate all of your javascript/jQuery into a separate file where it's easier to maintain and where it can stay out of the way of the content. I never did like seeing all those "javascript:void()" messages in the status bar when I would hover over a link. That's what happens when you attach the event directly inside an <a href>
tag.
On some pages that use traditional javascript, you'll see an "onload" attribute in the <body>
tag. The problem with this is that it's limited to only one function. Oh yeah, and it adds "behavioral" markup to the content again. Jeremy Keith's excellent book, DOM Scripting, showed me how to create an addLoadEvent function to a separate javascript file that allows for multiple functions to be loaded inside it. But it requires a fair amount of code for something that should be rather straightforward. Also, it triggers those events when the window loads, which leads me to another advantage of $(document).ready().
With $(document).ready()
, you can get your events to load or fire or whatever you want them to do before the window loads. Everything that you stick inside its brackets is ready to go at the earliest possible moment — as soon as the DOM is registered by the browser, which allows for some nice hiding and showing effects and other stuff immediately when the user first sees the page elements.
Update
I thought it might help the absolute beginners to see an example of the<head>
where you would include your scripts. Note that CSS stylesheets come before the jQuery file, and the jQuery file comes before your custom script:
It is in "yourcustomscript.js" that you would place your script inside the $(document).ready()
block.