Window and Document Events
In this page:
Window Load
Binding to the window's load event lets you run code only after every image, script, and stylesheet has fully finished loading. This makes it slower to fire than document ready, but safer when your code depends on image dimensions or external resources.
Example: Window Load
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
$(window).on("load", function() {
console.log("All resources fully loaded");
});
</script>
</body>
</html>
Window Resize
The resize event fires every time the browser window's dimensions change, which is commonly used to recalculate layout-dependent values like a canvas size or a responsive breakpoint.
Example: Window Resize
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
$(window).on("resize", function() {
console.log("Width:", $(window).width());
});
</script>
</body>
</html>
Window Scroll
The scroll event fires continuously as the user scrolls the page, often used to implement sticky headers, infinite-loading lists, or 'back to top' buttons that appear past a certain scroll position.
Example: Window Scroll
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div style="height:2000px">Scroll down</div>
<script>
$(window).on("scroll", function() {
console.log("Scroll top:", $(window).scrollTop());
});
</script>
</body>
</html>
Document Ready
Document ready runs when the HTML document's structure is fully parsed, which happens much earlier than the window's load event since it doesn't wait for images or external resources to finish downloading.
Example: Document Ready
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
$(document).ready(function() {
console.log("DOM structure is ready");
});
</script>
</body>
</html>
Document Events
Binding events at the document level, rather than to individual elements, lets a single handler catch events bubbling up from anywhere on the page -- the foundation of the event delegation pattern.
Example: Document Events
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button class="item">Click me</button>
<script>
$(document).on("click", ".item", function() {
console.log("Caught bubbled click");
});
</script>
</body>
</html>
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: