jQuery Tutorial

jQuery Document and Window Events


We can use the $(document) when the document is fully loaded.ready() method to run a function. 

All jQuery methods are contained within a document ready event:

// jQuery methods go here...

This prevents any jQuery code from being executed before the document has finished loading (is ready).

Before working with a document, it's a good idea to wait until it's fully loaded and ready. This also allows you to place your JavaScript code in the head section of your document before the body.

Here are several activities that may fail if methods are called before the document has fully loaded:

  • Trying to hide an element that has not yet been created

  • Trying to determine the size of an image that has not yet been loaded

Tip: The jQuery team has also created a method for the document ready event that is even shorter:

// jQuery methods go here...
});ry methods go here...

You can use whatever syntax you want. However, we believe the document-ready event is easier to understand when reading the code.

ready() Method

When the DOM is fully loaded, the jQuery ready() method specifies a function to run.

The following example will replace the paragraph text when the DOM hierarchy has been entirely constructed and is ready to be manipulated.

Example of jQuery ready method

resize() Method

When the browser window's size changes, the jQuery resize() method attaches an event handler function to the window element, which is executed.

When you try to resize the browser window by dragging its corners, look at the example below to check the current width and height of the browser window. 

Example of jQuery resize method

scroll() Method

When the element's scroll position changes, the jQuery scroll() method attaches an event handler function to the window or scrollable iframes and elements.

A message will appear when you scroll the browser window in the following example.

Example of jQuery scroll method

Did you find this article helpful?