Bootstrap

Bootstrap Js Affix

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.

html
<header id="mainHeader">My Sticky Header</header>
<main>
<p>Lots of content here...</p>
</main>

Basic Affix Logic (Vanilla JS)

javascript
const header = document.getElementById('mainHeader');
const sticky = header.offsetTop;

window.addEventListener('scroll', function () {
if (window.pageYOffset > sticky) {
header.classList.add('affixed');
} else {
header.classList.remove('affixed');
}
});

Then in your CSS:

css
.affixed {
position: fixed;
top: 0;
width: 100%;
background-color: #fff;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
z-index: 1000;
}

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.

Leave a Reply

Your email address will not be published. Required fields are marked *