Advertisement

Sticky Observer Navigation

| by Vladimir | 2 min read | code by Claire Larsen
Intermediate

Tech & Dependencies

HTML SCSS JavaScript

Features

  • Scroll Detection
  • Smooth Transitions
  • Performance Optimized
  • Responsive Nav

Browser Support

Chrome 51+ Edge 15+ Firefox 55+ Safari 12.1+

Core

The Sticky Observer Navigation is a performance-first header component designed for modern landing pages. It uses an elegant dark-blue color palette with “Abril Fatface” typography to create a high-contrast, premium look. The navigation intelligently shrinks and hides the central title as the user scrolls, providing more screen real estate for content while maintaining essential link icons within a fixed bar.

Core Technique

The technical heart of this snippet is the Intersection Observer API, which provides a significantly more efficient way to detect scroll position compared to the traditional window.onscroll event. Instead of constantly running code on every pixel scrolled, the script watches an invisible “sentinel” element (#observe-top) placed at the very top of the document. When this sentinel leaves the viewport (detected via boundingClientRect.y < 0), the observe-top class is added to the body. This state change triggers CSS transitions that handle the resizing of the container and the font-size reduction of the header.

Customization

You can easily adjust the “shrink” intensity and the appearance of the navigation by modifying the SCSS variables and the specific state-driven classes.

/* Adjust the transition speed and easing */
nav .container {
  /* Change 0.5s to 0.2s for a snappier feel */
  transition: max-width 0.5s ease-in-out, border 0.05s ease-in-out;
  
  .observe-top & {
    /* The width of the nav when scrolled */
    max-width: 95%; 
    border-bottom: 1px solid transparent;
  }
}

/* Adjust title hiding */
nav h2 {
  .observe-top & {
    /* Setting font-size to 0 hides it smoothly */
    font-size: 0;
  }
}

To change the point where the animation triggers, you can adjust the position of the sentinel element or add a rootMargin to the observer:

const observer = new IntersectionObserver((entries) => {
  // Logic remains same...
}, {
  /* Trigger 100px before reaching the top */
  rootMargin: '-100px 0px 0px 0px' 
});

Tips

1. Performance over Scroll Events: Always prefer Intersection Observer for UI state changes based on scroll. It prevents “jank” because the browser can optimize the observation, whereas scroll events fire hundreds of times per second and can block the main thread.

2. Accessibility Note: While this snippet uses font-size: 0 to hide the title, the text remains in the DOM for screen readers. However, ensure the icons used in the nav have proper aria-label attributes if you plan to use this in a production environment, as empty icons are not accessible.

Advertisement