Skip to content

Sticky navigation on scrolldown

Navigation bar is absolutely positioned at first, but gets a sticky class added if user scrolls far down enough

Tags that this post has been filed under. Links open in the same window.

let navbar = document.getElementById('navbar');
let mainpos = document.getElementById('main');
let navPos = mainpos.getBoundingClientRect().top;
window.addEventListener('scroll', e => {
let scrollPos = window.scrollY;
if (scrollPos > navPos) {
navbar.classList.add('sticky');
} else {
navbar.classList.remove('sticky');
}
});