← Back to Chapters

jQuery Document Ready

? jQuery Document Ready

? Quick Overview

The jQuery document ready function ensures that your JavaScript code runs only after the HTML document is fully loaded and ready to be manipulated.

? Key Concepts

  • Prevents JavaScript from running before DOM is loaded
  • Safer than placing scripts at the top of the page
  • Executes once when DOM is ready

⚡ DOM Ready vs. Window Load

It is important to understand the difference between $(document).ready() and window.onload.

Feature $(document).ready() window.onload
Trigger Time Runs as soon as HTML is parsed (Early). Runs after HTML, Images, and Styles are loaded (Late).
Multiple Usage Can differ multiple times; they run in order. Only the last function assigned will run.
Use Case Manipulating elements, binding events. Calculations dependent on image dimensions.

? Syntax / Theory

jQuery provides a built-in method to detect when the document is ready. This avoids errors caused by accessing elements before they exist.

? View Code Example
// Standard document ready syntax
$(document).ready(function() {
  console.log("DOM is fully loaded");
});

? Code Example(s)

? View Code Example
// Shorthand document ready syntax
$(function() {
  $("#msg").text("jQuery is ready!");
});

? Live Output / Explanation

Explanation

When the page loads, jQuery waits until the DOM is ready, then updates the content of the selected element safely.

? Interactive Example

Live Playground

Below is a real working example. The status box detects when the DOM is ready automatically.

Waiting for DOM...

? Success! jQuery handled this click event perfectly.
? View Source Code for Demo
// 1. Wait for DOM Ready
$(document).ready(function() {
  
  // 2. Update the visual indicator
  $("#dom-status").text("DOM IS READY ✅").addClass("ready");

  // 3. Bind the click event safely
  $("#interactive-btn").click(function() {
    $("#interactive-msg").slideDown(); // Animate visibility
    $(this).text("Clicked!"); // Change button text
  });

});

? Use Cases

  • Initializing plugins (Sliders, Carousels)
  • Binding event handlers (Clicks, Hovers)
  • Manipulating DOM elements safely (Hiding/Showing content)
  • Running scripts without waiting for heavy images to load

✅ Tips & Best Practices

  • Prefer shorthand syntax $(function(){...}) for cleaner code
  • Avoid multiple document ready blocks if possible to keep code organized
  • Keep initialization logic inside document ready, but define functions outside

? Try It Yourself

  • Change text of an element on page load
  • Hide an element when DOM is ready
  • Bind a click event using document ready