Document Ready Event
In this page:
Why Document Ready Matters
Running jQuery code before the HTML has finished loading means elements you try to select simply won't exist yet, so scripts fail silently.
Example: Why Document Ready Matters
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$("#msg").text("This fails silently, #msg does not exist yet");
</script>
</head>
<body>
<p id="msg">Original</p>
</body>
</html>
Basic Ready Syntax
$(document).ready(function(){...}) delays your code until the browser has finished parsing the full HTML structure, guaranteeing every element you reference in the callback actually exists in the DOM.
Example: Basic Ready Syntax
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p id="msg">Original</p>
<script>
$(document).ready(function() {
$("#msg").text("DOM is ready");
});
</script>
</body>
</html>
Ready with a Function
You can place any number of jQuery statements inside a single ready callback, and they'll all run together once the document is parsed -- this is where most beginner jQuery pages put their entire script.
Example: Ready with a Function
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p id="a">A</p><p id="b">B</p>
<script>
$(document).ready(function() {
$("#a").text("Updated A");
$("#b").text("Updated B");
});
</script>
</body>
</html>
Ready and Button Events
Attaching click and other event handlers inside document ready is essential, since binding a handler to an element that doesn't exist yet silently does nothing -- the handler simply never gets attached.
Example: Ready and Button Events
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="btn">Click</button>
<script>
$(document).ready(function() {
$("#btn").click(function() {
console.log("Handler attached inside ready, works correctly");
});
});
</script>
</body>
</html>
Modern Shorthand
The shorthand $(function(){...}) is functionally identical to $(document).ready(...) but shorter to type, and it's the form you'll see most often in real-world jQuery code and tutorials.
Example: Modern Shorthand
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p id="msg">Original</p>
<script>
$(function() {
$("#msg").text("Shorthand ready works too");
});
</script>
</body>
</html>
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: