jQuery Document Ready

shape Description

On some pages that use traditional javascript,in the body tag the attribute onload attribute is seen .But it is limited only single function. First thing, whenever using  jQuery to manipulate the web page, it is a good practice to wait until the document ready event has fired before working with the document page. The document ready event tells that the HTML DOM page is now ready. So one can manipulate HTML elements without worrying.

jQuery document ready event keeps the code from running before document finished loading and it is a decent practice to wait for the document till it is loaded completely.

shape Syntax

Document Ready Event

$(document).ready(function()
{
//DOM manipulation code
});

  • $ sign is used to define jQuery, passing to it the document object. The$ function returns enhanced version of document object and it has a ready()method with anonymous function.
  • Inside ready() method, one can execute all the jQuery and JavaScript code what they need, in order to enhance the HTML elements of the DOM.

Alternate/Shorter Method for Document Ready Event

The jQuery library is actually declared in a variable called jQuery. This variable doesn’t just hold a static value, but it is actually a function. So a jQuery statement runs the function. This adds the open and close parentheses() and is terminated by a semicolon; end up wrapping around on a few lines below.When the function is run, whatever statements that are inside the function, those run.

$(function()
{
// jQuery methods go here…
});

shape Description

Check the below example for more help


<html>
	<head>
	   <title>jQuery Document Ready</title>
	</head>

	<body>
	 
		<h1>Welcome to SPLessons</h1>
		<p>click on this paragraph</p>
		<span>This is a span element</span>
	 
	</body>
</html>

$(document).ready(function(){
   $("p").click(function() {
     alert("The Paragraph was clicked");
   })
}); 

Output: When clicked on the paragraph element the following output appears.

Summary

shape Points

  • Document ready() function gets executed only after all the DOM elements gets loaded.
  • $(document).ready(function(){}); is the syntax for ready function.