Skip to main content

Command Palette

Search for a command to run...

Event Listeners on the window Object in JavaScript

Published
4 min read

In frontend development, many important events don’t happen on buttons or inputs—they happen at the browser level. Things like resizing the window, scrolling the page, switching tabs, or going offline are all window-level events.

To respond to these, JavaScript provides event listeners on the window object.

This article explains:

  • What window event listeners are

  • How they work internally

  • The difference between event listening and event handling

  • How (and why) to remove event listeners

  • Common mistakes and best practices


1. What is the window Object?

window is the global browser object that represents the entire browser tab.

It:

  • Owns global variables and functions

  • Represents the viewport

  • Emits high-level browser events

Examples of events fired by window:

  • resize

  • scroll

  • load

  • beforeunload

  • focus / blur

  • online / offline

  • keydown, keyup


2. What is an Event Listener?

An event listener is a function registered to be notified when a specific event occurs on a target (like window, document, or an element).

Basic syntax

window.addEventListener("resize", () => {
  console.log("Window resized");
});

Here:

  • resize → event type

  • callback function → what should run when the event happens


3. How Window Event Listeners Work (Under the Hood)

The process looks like this:

  1. The browser detects an event (e.g., window resized)

  2. The browser creates an Event object

  3. The event is dispatched to the window

  4. Any registered listeners for that event are executed

  5. Each listener receives the event object

Example:

window.addEventListener("resize", (event) => {
  console.log(event.type); // "resize"
  console.log(window.innerWidth);
});

Important points:

  • The browser decides when the event fires

  • JavaScript only reacts via listeners

  • Multiple listeners can exist for the same event


4. Event Listening vs Event Handling (Important Distinction)

This confusion is very common.

Event Listening

Event listening means registering interest in an event.

window.addEventListener("scroll", onScroll);

You are saying:

“Call this function when the scroll event happens.”

This is passive setup.


Event Handling

Event handling is the logic that runs when the event fires.

function onScroll() {
  console.log("User is scrolling");
}

This is active behavior.


In short

ConceptMeaning
Event listeningAttaching a listener to an event
Event handlingExecuting logic in response to the event

A listener connects, a handler responds.


5. Common Window Events and Examples

Resize event

function handleResize() {
  console.log(window.innerWidth, window.innerHeight);
}

window.addEventListener("resize", handleResize);

Used for:

  • Responsive layouts

  • Recalculating dimensions

  • Canvas resizing


Scroll event

window.addEventListener("scroll", () => {
  console.log(window.scrollY);
});

Used for:

  • Infinite scroll

  • Sticky headers

  • Scroll-based animations

⚠️ Scroll events fire very frequently—be careful.


Load event

window.addEventListener("load", () => {
  console.log("All resources loaded");
});

Fires after:

  • HTML

  • CSS

  • Images

  • Fonts


Online / Offline detection

window.addEventListener("online", () => {
  console.log("Back online");
});

window.addEventListener("offline", () => {
  console.log("You are offline");
});

6. Removing Event Listeners (Very Important)

If you add a listener, you should remove it when it’s no longer needed.

Why removal matters

  • Prevents memory leaks

  • Avoids duplicate handlers

  • Stops unexpected behavior

  • Critical in SPAs (React, Vue, Angular)


How to remove a listener

You must pass the same function reference.

✅ Correct:

function handleResize() {
  console.log("Resized");
}

window.addEventListener("resize", handleResize);

// later
window.removeEventListener("resize", handleResize);

❌ Incorrect (will NOT work):

window.addEventListener("resize", () => {
  console.log("Resized");
});

window.removeEventListener("resize", () => {
  console.log("Resized");
});

Reason:

  • These are two different function objects

  • JavaScript cannot match them


7. Event Listener Options

once

Runs only once, then auto-removes itself.

window.addEventListener("load", () => {
  console.log("Loaded once");
}, { once: true });

passive

Improves scroll performance by telling the browser you won’t call preventDefault.

window.addEventListener("scroll", onScroll, { passive: true });

8. Event Listeners in React (Real-World Context)

In React, window listeners are usually added inside useEffect.

useEffect(() => {
  function handleResize() {
    console.log(window.innerWidth);
  }

  window.addEventListener("resize", handleResize);

  return () => {
    window.removeEventListener("resize", handleResize);
  };
}, []);

Key points:

  • Listener is added after mount

  • Cleanup removes it before unmount

  • Prevents multiple listeners on re-renders


9. Common Mistakes to Avoid

❌ Adding listeners inside loops or render logic
❌ Forgetting cleanup in SPAs
❌ Using anonymous functions when removal is needed
❌ Heavy logic inside scroll/resize handlers
❌ Confusing handler logic with listener registration


10. Mental Model to Remember

  • Events happen automatically

  • Listeners register interest

  • Handlers contain behavior

  • Cleanup is your responsibility

If you remember this model, you’ll avoid most bugs related to window events.