$(document).ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded.JavaScript:
// put all your jQuery goodness in here.
});
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 tag. On some pages that use traditional javascript, you'll see an "onload" attribute in the
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.Lets face it, nobody likes all those javascript:void(0); in the anchors href. As for that body “onload” function call, can that too, its no good. All that ugly code in the markup is just plain bad news.
With jQuery and document.ready() you can put all your event driven javascript in one file, making it easy to maintain and upgrade later. The document.ready() function works just as the name implies. Document refers to the DOM, or Document Object Model, while in this case “ready” refers to when the DOM is registered by the browser.
Before we start, make sure you have jQuery included on your page. For a quick refresh on how that’s done, click here.
Using the document.ready() function is really easy. Check out this example:
$(document).ready(function(){ //insert code here alert("this will flre when the DOM is loaded."); });
$(function(){ //insert code here alert("this will work the same as the code above."); });
$(document).ready(function(){ $('a').click(function(){ alert("you clicked me!"); }); });

