Document Ready

Run your jQuery code only after the page structure has fully loaded.

Syntax$(function () { // runs when the DOM is ready });

Your code should run only after the HTML is ready in the browser. jQuery gives you the ready handler for this.

Two equivalent ways to write it

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

// shorthand
$(function () {
  // your code here
});

Without it, a script in the <head> might run before the elements it targets exist, so selectors would find nothing.

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A form page wraps all validation logic in document ready so inputs exist in the DOM before event listeners attach.
  • A gallery script uses document ready to measure image container widths before calculating layout.
  • A sticky-nav component waits for document ready to read the header height before setting scroll offsets.

More examples

Classic document ready handler

The traditional $(document).ready() form runs the callback only after the HTML is parsed.

Example · html
<script>
$(document).ready(function () {
  console.log("DOM is fully parsed.");
  $("#title").text("Page is ready!");
});
</script>

Shorthand ready with function

The $(function(){}) shorthand is identical to $(document).ready() and is preferred for brevity.

Example · html
<script>
$(function () {
  $("button").on("click", function () {
    $("p").hide(400);
  });
});
</script>

Multiple ready handlers on one page

jQuery queues multiple ready handlers in order, letting plugins and app code each register independently.

Example · html
<script>
// plugin file
$(function () {
  $(".tooltip").each(function () {
    $(this).attr("title", $(this).data("tip"));
  });
});
// main app file
$(function () {
  $("#menu").show();
});
</script>

Discussion

  • Be the first to comment on this lesson.