Creating Sticky UI with JavaScript Affix: A Simple Guide
Ever noticed how some navigation bars or side elements stay in place as you scroll down a webpage? That’s the magic of an “affix” — a technique that keeps elements fixed to a position while the rest of the content moves. In this post, we’ll explore how to create a sticky (affixed) element using vanilla JavaScript—no jQuery or external libraries required.
What is an “Affix”?
An affix refers to an element that becomes “stuck” at a certain position in the viewport when you scroll. It’s commonly used for:
-
Navigation bars that stick to the top
-
Sidebar menus
-
Call-to-action buttons
-
Table of contents
Use Case
Let’s say we have a header we want to stick to the top of the page when a user scrolls past it.
Basic Affix Logic (Vanilla JS)
Then in your CSS:
Why Use JavaScript Instead of position: sticky?
While position: sticky is supported in most modern browsers, it has some quirks, especially with parent elements that have overflow: hidden or in older browser versions. JavaScript gives you full control and can add smooth transitions, animations, or toggle behaviors based on scroll position.
Advanced Affix Behaviors
-
Unpin on scroll up
-
Affix within a parent container
-
Sticky only after a delay or threshold
These can be layered in with JavaScript scroll listeners and logic — or handled with libraries like Bootstrap’s Affix (deprecated), or newer plugins like Stickybits or Headroom.js.
Final Thoughts
Implementing affix behavior with JavaScript is a small touch that can drastically improve usability and navigation. Whether you’re building a blog, documentation site, or a full-blown web app, this trick will keep your UI clean and your users happy.
