Window Events

Handle window and page events

IntermediateTopic: Events Programs
Back

JavaScript Window Events Program

This program helps you to learn the fundamental structure and syntax of JavaScript programming.

Try This Code
// Method 1: Load event
window.addEventListener('load', function() {
    console.log('Page fully loaded');
    // All resources loaded
});

// Method 2: DOMContentLoaded (faster)
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM ready');
    // DOM ready, images may still load
});

// Method 3: Before unload
window.addEventListener('beforeunload', function(e) {
    e.preventDefault();
    e.returnValue = ''; // Chrome requires returnValue
    return ''; // Some browsers
    // Shows confirmation dialog
});

// Method 4: Unload
window.addEventListener('unload', function() {
    console.log('Page unloading');
    // Cleanup code
});

// Method 5: Resize
window.addEventListener('resize', function() {
    console.log('Window resized');
    console.log('Width:', window.innerWidth);
    console.log('Height:', window.innerHeight);
});

// Method 6: Scroll
window.addEventListener('scroll', function() {
    console.log('Scrolled');
    console.log('Scroll Y:', window.scrollY);
    console.log('Scroll X:', window.scrollX);
});

// Method 7: Scroll with throttling
let scrollTimeout;
window.addEventListener('scroll', function() {
    clearTimeout(scrollTimeout);
    scrollTimeout = setTimeout(function() {
        console.log('Scroll ended');
    }, 150);
});

// Method 8: Visibility change
document.addEventListener('visibilitychange', function() {
    if (document.hidden) {
        console.log('Page hidden');
    } else {
        console.log('Page visible');
    }
});

// Method 9: Online/Offline
window.addEventListener('online', function() {
    console.log('Connection restored');
});

window.addEventListener('offline', function() {
    console.log('Connection lost');
});

// Method 10: Focus/Blur
window.addEventListener('focus', function() {
    console.log('Window focused');
});

window.addEventListener('blur', function() {
    console.log('Window blurred');
});

// Method 11: Hash change (URL fragment)
window.addEventListener('hashchange', function() {
    console.log('Hash changed:', window.location.hash);
});

// Method 12: Popstate (back/forward)
window.addEventListener('popstate', function(e) {
    console.log('History changed');
    console.log('State:', e.state);
});

// Method 13: Error handling
window.addEventListener('error', function(e) {
    console.error('Global error:', e.message);
    console.error('File:', e.filename);
    console.error('Line:', e.lineno);
});

window.addEventListener('unhandledrejection', function(e) {
    console.error('Unhandled promise rejection:', e.reason);
});
Output
// Output depends on window events

Understanding Window Events

Window events handle page lifecycle.

Load Events

load: All resources loaded
DOMContentLoaded: DOM ready (faster)
beforeunload: Before page unloads
unload: Page unloading

Window Events

resize: Window resized
scroll: Page scrolled
focus/blur: Window focus

Page Visibility

visibilitychange: Tab visibility
hidden: Page hidden
visible: Page visible

Network Events

online: Connection restored
offline: Connection lost

Navigation Events

hashchange: URL hash changed
popstate: History navigation

Error Events

error: Global errors
unhandledrejection: Promise errors

Use Cases

Page initialization
Cleanup on exit
Responsive design
Analytics tracking

Let us now understand every line and the components of the above program.

Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.

Practical Learning Notes for Window Events

This JavaScript program is part of the "Events Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents