jquery
  1. jquery-document-ready

JQuery Document Ready

JQuery's document ready function is a useful tool for executing JavaScript code when the DOM is fully loaded and ready for manipulation.

Syntax

The basic syntax for using the document ready function in JQuery is:

$(document).ready(function() {
  // Your JavaScript code goes here
});

Alternatively, you can use a shorthand notation for the document ready function:

$(function() {
  // Your JavaScript code goes here
});

Both of these syntax options accomplish the same thing - they wait for the DOM to be fully loaded before executing the JavaScript code within the function.

Use

The document ready function is particularly useful for manipulating the DOM with jQuery, as you can be sure that all the necessary elements are loaded before attempting to modify their properties, values, or attributes. It is also useful for binding events to elements, such as clicking, hovering, or scrolling.

Example

Here is an example of how to use the document ready function in JQuery:

<!DOCTYPE html>
<html>
<head>
  <title>Document Ready Example</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
  <h1>Hello World</h1>

  <script>
    $(document).ready(function() {
      $('h1').css('color', 'red');
    });
  </script>
</body>
</html>
Try Playground

In this example, we use the document ready function to change the color of the h1 element to red as soon as the DOM is fully loaded. Without this function, the JavaScript code might run before the h1 element is available, resulting in an error.

Summary

JQuery's document ready function is a powerful tool for ensuring that your JavaScript code executes only when the DOM has been fully loaded. Using this function can help avoid errors and ensure that your code is executed at the appropriate time. As such, it is a valuable tool for any web developer who wants to use JQuery to manipulate the DOM or bind events to elements.

Published on: