jQuery's document.ready(), What is it and Why is it Useful?
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.");
});
As with most code, there is a shorthand version of the document.ready() function. In jQuery, any function passed to the jQuery object will be bound to the document.ready() function, as seen below.
$(function(){
//insert code here
alert("this will work the same as the code above.");
});
This is how you would add a click event to all the anchor tags on your page using the document.ready() function.
$(document).ready(function(){
$('a').click(function(){
alert("you clicked me!");
});
});
That’s all there is to it. Are you having an issue with jQuery, or any code you need some help on? Have an idea for an article you’d like to see? Feel free to leave a comment with any questions or suggestions.
awesome, i really like the post and the previous one, i have been looking for some series of posts like this to learn jquery hope you keep posting, also this is going to my feeds thanks