jQuery Start

Posted: February 12, 2013 in Java Scripts

The Document Ready Event

You might have noticed that all jQuery methods in our examples, are inside a document ready event:
$(document).ready(function(){

// jQuery methods go here…

});

This is to prevent any jQuery code from running before the document is finished loading (is ready).

It is good practice to wait for the document to be fully loaded and ready, before working with it. This also allows you to have your JavaScript code before the body of your document, in the head section.

Here are some examples of actions that can fail if methods are run before the document is fully loaded:

Trying to hide an element that is not created yet
Trying to get the size of an image that is not loaded yet

Tip: The jQuery team has also created an even shorter method for the document ready event:
$(function(){

// jQuery methods go here…

});

Use the syntax you prefer. We think that the document ready event is easier to understand when reading the code.

=============================================================================================

$(document).ready(function(){
$(“p”).click(function(){
$(this).hide();
});
});

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s