Skip to content

Instantly share code, notes, and snippets.

@steveshead
Last active February 6, 2021 18:11
Show Gist options
  • Save steveshead/5d7c82f90ae5db728291e66c07d426ea to your computer and use it in GitHub Desktop.
Save steveshead/5d7c82f90ae5db728291e66c07d426ea to your computer and use it in GitHub Desktop.
[Javascript Sticky Nav] vanilla javascript sticky nav with offset using the Intersection Observer API
const header = document.querySelector('.header');
const navHeight = nav.getBoundingClientRect().height;
const stickyNav = function (entries) {
const [entry] = entries;
if (!entry.isIntersecting) nav.classList.add('sticky');
else nav.classList.remove('sticky');
};
const headerObserver = new IntersectionObserver(stickyNav, {
root: null,
threshold: 0,
rootMargin: `-${navHeight}px`,
});
headerObserver.observe(header);
/*
Assumption is you have a 'nav' class - plus you'll need to add the CSS below to your stylesheet:
.nav.sticky {
position: fixed;
background-color: rgba(255, 255, 255, 0.95);
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment