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.
jQuery window events are attached using the $(window) selector. You can bind events using shorthand methods or the .on() method.
// General syntax for window events
$(window).eventName(function() {
// Code to execute when event occurs
});
// Detect when the page is fully loaded
$(window).on("load", function() {
alert("Page fully loaded");
});
// Detect window resize event
$(window).resize(function() {
console.log("Window resized");
});
// Detect scroll position of the window
$(window).scroll(function() {
console.log($(window).scrollTop());
});
Resize or scroll the browser window and open the developer console to observe real-time event detection.
.on() for better event control