When working with jQuery, it is a good idea to wait for the document to be fully loaded, prior to executing jQuery code on the page. One of the first things you should learn about jQuery is the ready event. Most of your jQuery code will be contained within this handler.
This will ensure that the jQuery code does not run until the DOM is ready. It will confirm that any element being accessed is already loaded and accessible, so the script will not return any errors related to missing elements.
In addition, it also ensures that your code is unobtrusive. The ready event occurs when the DOM (document object model) has been loaded, and the page has been completely rendered (including images).
Because this event occurs after the document is ready, it is generally used to have all jQuery events and functions. The ready()
method can only be used on the current document, so no selector is required. The following syntaxes are accepted:
Syntax
$(document).ready(function)
$().ready(function)
$(function)
Parameter | Description |
---|---|
function | Specifies the function to run when the document is loaded. |
HTML Example
We will use the following HTML for the example listed below.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// ... jQuery Code ...
});
</script>
</head>
<body>
<div id="div1"> <!-- Some Content --> </div>
</body>
</html>
Example
The text within the span element is updated each time the mouse icon is clicked.
<script type="text/javascript">
var a = 0;
$("img").click(function(){
$("span").text(++a)
});
</script>