# Observer APIs: Intersection, Mutation & Resize

> Stop using terrible scroll and resize event hacks. Discover the modern, highly-optimized Observer APIs that let you respond to layout and DOM changes efficiently.

Subject: JavaScript | Lesson 38 of 63 | 7 min read
Interactive lesson: https://codewithanimation.in/javascript/observer-apis
Previous: [Timers & requestAnimationFrame](https://codewithanimation.in/javascript/timers-and-raf.md) | Next: [Web Workers & Off-Main-Thread](https://codewithanimation.in/javascript/web-workers.md)

## The Performance Saviors

In the past, if you wanted to know when an element scrolled onto the screen, you had to attach an event listener to the `window.onscroll` event.

Because the user scrolls hundreds of pixels a second, your function would fire hundreds of times a second, bringing the browser to a crawl. The modern **Observer APIs** were created to solve this.

## The Big Three

1. `IntersectionObserver`: Tells you exactly when an element enters or leaves the screen (or another container). Used for lazy-loading images and infinite scrolling.

2. `ResizeObserver`: Tells you when a specific element changes its width or height. It is a massive improvement over listening to `window.onresize`.

3. `MutationObserver`: Tells you when the DOM tree itself changes, such as a node being added/removed or a class name changing.

## The Standard Pattern

All observers follow the exact same architectural pattern:

First, you instantiate the observer with a callback function: `const observer = new IntersectionObserver((entries) => { ... })`.

Second, you tell it what element to watch: `observer.observe(myDiv)`.

When the criteria is met, the browser fires your callback asynchronously, passing an array of `entries` containing the new data.

## Common mistake: Memory Leaks

Observers are powerful, but they are also a massive source of memory leaks in Single Page Applications (like React).

If you tell an observer to watch an element, and then that element is removed from the DOM (because the user navigated to a different page), the observer will keep holding onto it in memory.

You must always call `observer.disconnect()` when you are done to free up the system's RAM.

## Tip: Thresholds

The `IntersectionObserver` takes an optional `threshold` array. If you pass `threshold: [0, 0.5, 1]`, your callback will fire when the element is 0% visible, 50% visible, and exactly 100% visible.

## Try it: The Intersection Simulator

Scroll the container below. Watch how the observer only fires its callback at the exact moment the target element crosses the threshold, saving immense amounts of CPU power compared to a scroll listener.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/javascript/observer-apis

## Check yourself

### Question 1

Why is `IntersectionObserver` better than a `window.addEventListener('scroll')` hack?

- A. It only fires when the element actually crosses the threshold, rather than firing on every single pixel scrolled.
- B. It runs on a Web Worker.
- C. It automatically downloads images for you.

Correct answer: A

Scroll events fire synchronously hundreds of times a second. `IntersectionObserver` calculates the math natively in the browser engine and only wakes up your JavaScript when the exact threshold is crossed.

- Why not B: Incorrect. It runs on the main thread, but it is highly optimized by the browser engine.
- Why not C: Incorrect. It just gives you the timing; you still have to write the code to download the image.

### Question 2

If you want to run a function every time a specific `<div>` is made wider by CSS Grid or Flexbox, what should you use?

- A. ResizeObserver
- B. window.onresize
- C. MutationObserver

Correct answer: A

`ResizeObserver` allows you to watch individual elements for dimension changes, regardless of whether the main browser window changed size.

- Why not B: Incorrect. That only fires when the entire browser window resizes, not when internal elements change size due to layout shifts.
- Why not C: Incorrect. MutationObserver watches the DOM tree nodes and attributes, not computed physical dimensions.

### Question 3

What critical step must you take when an observed element is removed from the screen?

- A. Call observer.disconnect() or observer.unobserve(element) to prevent memory leaks.
- B. Call element.remove() a second time.
- C. Set the observer variable to null.

Correct answer: A

Observers hold strong references to the DOM nodes they are watching. Failing to disconnect them when a component unmounts is a classic cause of memory leaks.

- Why not B: Incorrect. Removing it from the DOM doesn't remove it from the observer's internal memory array.
- Why not C: Incorrect. The browser API engine itself is still holding the reference until you explicitly disconnect it.

## Remember this

- Stop using `scroll` and `resize` event listeners for layout calculations.
- `IntersectionObserver` fires when elements enter or leave a container.
- `ResizeObserver` fires when an element's physical dimensions change.
- `MutationObserver` fires when DOM nodes or attributes are modified.
- Always call `observer.disconnect()` to prevent memory leaks when elements are destroyed.
