Using $(document).ready()

Contact Us or call 1-877-932-8228
Using $(document).ready()

Using $(document).ready()

You cannot safely manipulate a page until the document is "ready." jQuery detects this state of readiness for you; code included inside $(document).ready() will only run once the page is ready for JavaScript code to execute.

A $(document).ready() Block

Code Sample:

jqy-concepts/Demos/document-ready.html
<html>
<head>
<script src="../../jqy-libs/jquery.js"></script> 
<script src="../../jqy-libs/fix-console.js"></script> 
<script>
$(document).ready(function() {
    console.log('ready!');
});
</script>
</head>
<body>
<p>We'll let you know when the document is ready ...</p>
</body>
</html>

There is a shorthand for $(document).ready() that you will sometimes see; however, I recommend against using it if you are writing code that people who aren't experienced with jQuery may see.

Shorthand for $(document).ready()

Code Sample:

jqy-concepts/Demos/document-ready-short.html
<html>
<head>
<script src="../../jqy-libs/jquery.js"></script> 
<script src="../../jqy-libs/fix-console.js"></script> 
<script>
$(function() {
    console.log('ready!');
});
</script>
</head>
<body>
<p>We'll let you know when the document is ready ...</p>
</body>
</html>

You can also pass a named function to $(document).ready() instead of passing an anonymous function.

Passing a Named Function Instead of an Anonymous Function

Code Sample:

jqy-concepts/Demos/passing-named-function.html
<html>
<head>
<script src="../../jqy-libs/jquery.js"></script> 
<script>
function readyFn() {
	alert("Document is ready");
}

$(document).ready(readyFn);
</script>
</head>
<body>
<p>We'll let you know when the document is ready ...</p>
</body>
</html>
Next