Last active
February 6, 2021 18:11
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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