← Back to Chapters

jQuery Window Events

? jQuery Window Events

? Quick Overview

Window events in jQuery allow you to detect and respond to browser-level actions such as page load, resize, scroll, and unload. These events are attached to the window object and are useful for building responsive, interactive web pages.

? Key Concepts

  • load – Triggered when the entire page loads
  • resize – Triggered when the window size changes
  • scroll – Triggered when the user scrolls
  • unload – Triggered when the page is closed or refreshed

? Syntax / Theory

jQuery window events are attached using the $(window) selector. You can bind events using shorthand methods or the .on() method.

? View Code Example
// General syntax for window events
$(window).eventName(function() {
// Code to execute when event occurs
});

? Code Example(s)

? View Code Example
// Detect when the page is fully loaded
$(window).on("load", function() {
alert("Page fully loaded");
});
? View Code Example
// Detect window resize event
$(window).resize(function() {
console.log("Window resized");
});
? View Code Example
// Detect scroll position of the window
$(window).scroll(function() {
console.log($(window).scrollTop());
});

? Live Output / Explanation

What Happens?

  • An alert appears when the page finishes loading
  • Console logs update when the browser window is resized
  • Scroll position values are logged as you scroll

? Interactive Example

Resize or scroll the browser window and open the developer console to observe real-time event detection.

? Use Cases

  • Creating responsive layouts
  • Implementing infinite scrolling
  • Detecting screen size changes
  • Lazy loading images or content

? Tips & Best Practices

  • Use .on() for better event control
  • Throttle or debounce scroll and resize events
  • Avoid heavy logic inside scroll handlers

? Try It Yourself

  • Display window width and height on resize
  • Change header color when scrolling down
  • Show a button when the user scrolls to bottom