Explain Codes LogoExplain Codes Logo

How to make div fixed after you scroll to that div?

javascript
css-positioning
sticky-elements
intersection-observer-api
Nikita BarsukovbyNikita BarsukovΒ·Jan 20, 2025
⚑TLDR

Toggle a fixed class on your div once it gets to the top of the viewport:

window.onscroll = () => { // 'fixMe' is about to 'fix' your scrolling problem πŸ‘ const div = document.getElementById('fixMe'); window.scrollY >= div.offsetTop ? div.classList.add('fixed') : div.classList.remove('fixed'); };

Define the .fixed class in CSS. This is magic that 'freezes' the div in place:

.fixed { position: fixed; top: 0; // With 'fixed', 'top: 0' is like 'top of the world' 🌍 }

How does fixed positioning work?

Understanding position: fixed is crucial. This CSS positioning makes the element positioned relative to the viewport. It means it's locked in place, even when the page is scrolled.

To accomplish "stickiness" after scrolling past a div, we use JavaScript. The window.onscroll event, along with window.scrollY and the element’s offsetTop, can add or remove the 'fixed' class dynamically.

Different strokes for different folks

A sticky alternative (CSS-only solution)

position: sticky could be your fancy CSS-only friend:

#fixMe { position: -webkit-sticky; // (Because Safari likes to play hard to get πŸ˜‰) position: sticky; top: 0; }

Initially, sticky behaves like relative, but after a certain offset, it turns into fixed.

API to the rescue: Intersection Observer

A next-level solution using the Intersection Observer API. This API detects the visibility of elements efficiently.

Winning the z-index war

Ensure your div rises above the rest using a higher `z-index:

.fixed { position: fixed; top: 0; z-index: 1000; // (Because over 9000 would be an overkill πŸ‰) }

Catering to all sizes and smoothing the ride

Make it responsive

Mind the width, left, or right properties, and adjust margins. Keep your fixed div in shape, regardless of the screen size.

Smoother than a fresh jar of Skippy

Add CSS transitions for a 'smooth' position change experience:

#fixMe { transition: top 0.3s; // (Like butter on a hot toast 🍞) }

Saving performance by debouncing

Debounce or throttle high-frequency scroll events. It's like telling your browser to hold its horses 🐎 and update only when necessary.