# Change Page Header on Scroll Using the Intersection Observer API

> *Originally published on Medium (JavaScript in Plain English). [Read on Medium for free via Friend Link](https://javascript.plainenglish.io/change-page-header-on-scroll-using-intersection-observer-api-a-dynamic-ux-approach-d09659a50e3d?sk=22f3338479cbeab39b69de180f26532e).*
>
> ☕ **[Explore Developer Starter Kits & Guides](https://www.buymeacoffee.com/mkare/extras)**

### Quick Takeaways

- **Zero scroll-listener overhead:** [Intersection Observer](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API) fires asynchronously only when visibility crosses a threshold—no `window.onscroll` throttling needed.
- **One-line class toggle:** Observing a lightweight sentinel `<div>` above your content lets `header.classList.toggle("active", !entry.isIntersecting)` drive the sticky transition.
- **Pure CSS offset control:** Adjusting `top` on `[data-observer-intercept]` delays the header transition until the user scrolls past an exact pixel threshold.

* * *

![Sticky page header changing background and shadow on scroll using the JavaScript Intersection Observer API](https://cdn-images-1.medium.com/max/800/1*H4sOuyKTvt0Hq6Fc_ucpSQ.jpeg)
*Using the Intersection Observer API to toggle a sticky header's active styles as the page scrolls.*

### Why Intersection Observer Beats Scroll Listeners

The Intersection Observer API helps us determine whether an element is currently visible within the user's viewport or has scrolled out of view. Instead of firing on every pixel of scroll, it notifies your callback only when visibility changes. By utilizing this API, we can create a header that dynamically adjusts its appearance as the user scrolls through the page.

Let's start with a minimal example that watches a single box element as it enters and leaves the viewport:

```html
<!DOCTYPE html>
<html>
<head>
  <style>
    .box {
      width: 200px;
      height: 200px;
      background-color: red;
      margin: 1000px auto;
    }

    .box.active {
      background-color: green;
    }
  </style>
</head>
<body>
  <div class="box"></div>

  <script>
    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          // Box is visible: add the "active" class
          entry.target.classList.add("active");
        } else {
          // Box is hidden: remove the "active" class
          entry.target.classList.remove("active");
        }
      });
    });

    const box = document.querySelector(".box");
    observer.observe(box);
  </script>
</body>
</html>
```

In this example, we create a box element and use the Intersection Observer to track its visibility. Initially, the box is off-screen. However, when the box becomes visible, we add the `active` class to it, giving it a green background color. When the box scrolls out of view again, we remove the `active` class, and it returns to red.

The Intersection Observer watches whether the box is visible within the page and reacts accordingly. That same pattern is all we need to build a scroll-aware sticky header.

* * *

![Diagram showing an invisible intercept sentinel div triggering a fixed sticky header class change on scroll](https://cdn-images-1.medium.com/max/800/1*m7_kUaNYY9fc-sIi2hukCA.png)
*Observing a lightweight sentinel element above the main content lets the header react to scroll without a scroll listener.*

### Change Page Header on Scroll

Here is the complete, self-contained HTML implementation for a sticky header that transitions its background, text color, and drop shadow once the user scrolls past the top of the page:

```html
<!DOCTYPE html>
<html>
  <head>
    <style>
      header {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        background-color: #f5f6fa;
        padding: 10px;
        z-index: 999;
      }

      /* Avoid content overlap under the fixed header */
      body {
        margin-top: 50px;
      }

      /* Extra height to enable page scrolling */
      .content {
        height: 2000px;
      }

      header.active {
        background-color: #273c75;
        box-shadow: hsla(0 0% 0% / 0.1) 0 0.5rem 1rem;
        color: #f5f6fa;
        transition-duration: 400ms;
      }
    </style>
  </head>
  <body>
    <header id="header">
      <h1>Sticky Header</h1>
    </header>

    <div class="content">
      <!-- Your page content goes here -->
    </div>

    <script>
      const header = document.getElementById("header");
      const intercept = document.createElement("div");
      const content = document.querySelector(".content");

      intercept.setAttribute("data-observer-intercept", "");
      content.before(intercept);

      const observer = new IntersectionObserver(([entry]) => {
        const scrolledPast = !entry.isIntersecting;
        header.classList.toggle("active", scrolledPast);
      });

      observer.observe(intercept);
    </script>
  </body>
</html>
```

The callback function of the Intersection Observer extracts the first `entry` from the array of entries using `([entry])`. It then uses `classList.toggle` to add the `active` class to the header when `entry.isIntersecting` is `false` (meaning the sentinel has scrolled out of the viewport) and remove it when `entry.isIntersecting` is `true`.

> **Tip:** Save the code in an HTML file and open it in a web browser to see the sticky header transition into its active state as you scroll. Feel free to adjust the colors, shadow, and transition duration to match your design system.

* * *

### How the Intercept Sentinel Works Step by Step

First, grab the header, create a lightweight intercept element, and select the main content container:

```js
const header = document.getElementById("header");
const intercept = document.createElement("div");
const content = document.querySelector(".content");
```

Next, tag the intercept element with a data attribute so we can target it cleanly in CSS:

```js
intercept.setAttribute("data-observer-intercept", "");
```

Insert the intercept element directly before the content container:

```js
content.before(intercept);
```

Create an Intersection Observer and start watching the intercept element:

```js
const observer = new IntersectionObserver(([entry]) => {
  const scrolledPast = !entry.isIntersecting;
  header.classList.toggle("active", scrolledPast);
});

observer.observe(intercept);
```

With the intercept `<div>` in place, we have a dedicated sentinel point on the page to observe. Whenever that sentinel enters or leaves the viewport, the Intersection Observer fires and toggles the header's `active` class.

When inspecting the DOM using the browser's developer tools, you will see the following structure:

```html
<div data-observer-intercept></div>
<header id="header">
  <!-- Header content goes here -->
</header>
```

Additionally, you can control *when* the header transitions by positioning the intercept element with CSS:

```css
[data-observer-intercept] {
  position: absolute;
  top: 200px;
}
```

When scrolling the page, the header shadow and active background won't appear immediately. Instead, the transition waits until the page has scrolled past the 200-pixel offset.

* * *

### Keep Exploring

- [Why Does Canvas Look Blurry on Retina Displays? devicePixelRatio and the Tale of Two Sizes](https://javascript.plainenglish.io/why-does-canvas-look-blurry-on-retina-displays-devicepixelratio-and-the-tale-of-two-sizes-2be8f6e6f7f8)
- [HTML Native Dialog Component in React with Tailwind CSS](https://javascript.plainenglish.io/html-native-dialog-component-in-react-with-tailwind-css-2b23356ef036)
- [Best Practices for Using TypeScript with React](https://javascript.plainenglish.io/best-practices-for-using-typescript-with-react-bad13d851143)
- [Toolkit & Starter Kits on Buy Me a Coffee](https://www.buymeacoffee.com/mkare)

How are you handling sticky headers and scroll-triggered UI transitions in your projects? I'd love to hear your approach 🧠💬

* * *

### 👋 About the Author

**Mustafa Morbel** is a senior software engineer and engineering leader with over 17 years of experience building web applications, frontend architectures, and developer tools.
