To detect when position: sticky is triggered with JavaScript, we use the intersection observer.
For instance, we write
const stickyElm = document.querySelector("header");
const observer = new IntersectionObserver(
([e]) => e.target.classList.toggle("isSticky", e.intersectionRatio < 1),
{ threshold: [1] }
);
observer.observe(stickyElm);
to create a new IntersectionObserver
object by calling it with a callback and an object.
The callback is called if the element we’re watching has intersected with the edge of the browser tab or window.
In it, we call classList.toggle
to toggle the isSticky
class to true
if the intersectionRatio
is less than 1, which means it is moving away from the edge of the screen.
We call observer
to watch the stickyElm
element for intersection.