Cover Image for jQuery ready() function
133 views

jQuery ready() function

The jQuery ready() function, also known as the $(document).ready() method, is used to specify a function to be executed when the DOM (Document Object Model) is fully loaded and ready to be manipulated by JavaScript and jQuery.

The ready() function is essential because it ensures that your JavaScript code is executed only after the entire HTML document has been parsed and all the DOM elements are available. This way, you can safely interact with and manipulate the elements on the page without worrying about elements not yet being loaded.

Here’s the basic syntax of the ready() function:

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

It is common to use the shorthand version of the ready() function, which uses the dollar sign notation:

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

Both versions achieve the same result, waiting for the DOM to be ready before executing the code inside the function.

Example:

<!DOCTYPE html>
<html>
<head>
  <title>jQuery ready() Function Example</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
  <div id="myDiv">This content will be changed after the page is ready.</div>

  <script>
    // jQuery ready function
    $(function() {
      // Code to execute after the DOM is ready
      $("#myDiv").text("Hello, this content has been changed!");
    });
  </script>
</body>
</html>

In this example, the content of the myDiv element is modified using jQuery inside the ready() function. The function ensures that the modification takes place only when the DOM is fully loaded.

By using the ready() function, you can ensure that your JavaScript code runs at the right time and avoid issues related to accessing elements that have not been loaded yet. It is considered a best practice to wrap your jQuery code inside the ready() function to make sure your code behaves as expected.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS