Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Window Events in JavaScript

Handle window events in JavaScript: load vs DOMContentLoaded, beforeunload, resize, scroll with debounce, online and hashchange. Explanation and output.

IntermediateJavaScript Events ProgramsExample 8 of 10

Put this script in a web page and open it in a browser. Resize, scroll, switch tabs and change the URL hash to trigger the events.

window-events.js
1// Method 1: Load event
2window.addEventListener('load', function() {
3 console.log('Page fully loaded');
4 // All resources loaded
5});
6
7// Method 2: DOMContentLoaded (faster)
8document.addEventListener('DOMContentLoaded', function() {
9 console.log('DOM ready');
10 // DOM ready, images may still load
11});
12
13// Method 3: Before unload
14window.addEventListener('beforeunload', function(e) {
15 e.preventDefault();
16 e.returnValue = ''; // Chrome requires returnValue
17 return ''; // Some browsers
18 // Shows confirmation dialog
19});
20
21// Method 4: Unload
22window.addEventListener('unload', function() {
23 console.log('Page unloading');
24 // Cleanup code
25});
26
27// Method 5: Resize
28window.addEventListener('resize', function() {
29 console.log('Window resized');
30 console.log('Width:', window.innerWidth);
31 console.log('Height:', window.innerHeight);
32});
33
34// Method 6: Scroll
35window.addEventListener('scroll', function() {
36 console.log('Scrolled');
37 console.log('Scroll Y:', window.scrollY);
38 console.log('Scroll X:', window.scrollX);
39});
40
41// Method 7: Scroll with throttling
42let scrollTimeout;
43window.addEventListener('scroll', function() {
44 clearTimeout(scrollTimeout);
45 scrollTimeout = setTimeout(function() {
46 console.log('Scroll ended');
47 }, 150);
48});
49
50// Method 8: Visibility change
51document.addEventListener('visibilitychange', function() {
52 if (document.hidden) {
53 console.log('Page hidden');
54 } else {
55 console.log('Page visible');
56 }
57});
58
59// Method 9: Online/Offline
60window.addEventListener('online', function() {
61 console.log('Connection restored');
62});
63
64window.addEventListener('offline', function() {
65 console.log('Connection lost');
66});
67
68// Method 10: Focus/Blur
69window.addEventListener('focus', function() {
70 console.log('Window focused');
71});
72
73window.addEventListener('blur', function() {
74 console.log('Window blurred');
75});
76
77// Method 11: Hash change (URL fragment)
78window.addEventListener('hashchange', function() {
79 console.log('Hash changed:', window.location.hash);
80});
81
82// Method 12: Popstate (back/forward)
83window.addEventListener('popstate', function(e) {
84 console.log('History changed');
85 console.log('State:', e.state);
86});
87
88// Method 13: Error handling
89window.addEventListener('error', function(e) {
90 console.error('Global error:', e.message);
91 console.error('File:', e.filename);
92 console.error('Line:', e.lineno);
93});
94
95window.addEventListener('unhandledrejection', function(e) {
96 console.error('Unhandled promise rejection:', e.reason);
97});

Sample Output

DOM ready

Printed before Page fully loaded, because the HTML is ready before images finish.

Scroll ended

Printed once, 150 ms after the last scroll event.

In this one

  • The difference between load and DOMContentLoaded
  • How resize and scroll work
  • How debouncing reduces work during scroll
  • How to catch page visibility, network, navigation and error events

How it works

  1. 1

    load and DOMContentLoaded log when the page is ready.

  2. 2

    beforeunload asks for confirmation before leaving.

  3. 3

    resize logs the new width and height.

  4. 4

    scroll logs positions and a timer logs Scroll ended.

  5. 5

    visibility, online, focus, hash and history changes are logged.

  6. 6

    error and unhandledrejection catch global problems.

Edge cases

beforeunload message ignored

Your custom text does not appear.

Browsers show their own generic message to stop abuse.

unload unreliable

Code in unload may not run on mobile.

Use visibilitychange or pagehide for saving state.

Heavy scroll handlers

Logging on every scroll makes the page lag.

Debounce, throttle, or use IntersectionObserver.

What's going on

Window events tell you about the whole page, not one element. They cover the page lifecycle, the size of the window, the network and navigation.

Load events come first. load fires when everything is loaded, including images. DOMContentLoaded fires earlier, as soon as the HTML is parsed. Images may still be loading. Use DOMContentLoaded when you only need the elements to exist. It is faster.

beforeunload fires just before the user leaves. Setting e.returnValue asks the browser to show a "Leave site?" confirmation. Chrome needs returnValue. Browsers show their own text, not yours. unload fires as the page goes away and was used for cleanup, but modern browsers are phasing it out.

resize fires when the window size changes. It gives innerWidth and innerHeight, useful for responsive design. scroll fires as the page scrolls and gives scrollX and scrollY.

Scroll can fire dozens of times a second. Method 7 clears and restarts a 150 ms timer on every scroll, so "Scroll ended" logs only after scrolling stops. This is debouncing, a way to wait until events stop. The code comment calls it throttling, but throttling means running at most once per time period.

visibilitychange tells you if the tab is hidden or visible. document.hidden is true when hidden. You might pause a video or a timer then. online and offline report when the connection is restored or lost.

focus and blur on window fire when the user switches to or away from the window. hashchange fires when the part after # in the URL changes. popstate fires on back and forward navigation.

error catches uncaught errors and gives the message, file and line. unhandledrejection catches promise errors nobody handled. Use cases include page setup, cleanup on exit, responsive design and analytics.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Which event fires when the tab is hidden?

Pick an answer to check it.

Question 2

What does Method 7 do?

Pick an answer to check it.

Questions people ask

Which fires first, load or DOMContentLoaded?

DOMContentLoaded. load waits for images and styles too.

What is the difference between debounce and throttle?

Debounce waits until events stop. Throttle runs at most once per time period.

Does hashchange reload the page?

No. Only the part after # changes.