Skip to content

Instantly share code, notes, and snippets.

@genesis16
Created March 2, 2023 01:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save genesis16/0e67d301038a4866043d7c33971cdb25 to your computer and use it in GitHub Desktop.
Save genesis16/0e67d301038a4866043d7c33971cdb25 to your computer and use it in GitHub Desktop.
Sticky nav
const stickyNav = document.querySelector('.site-header')
const header = document.getElementById('n2-ss-2')
const navHeight = document.querySelector('.site-header').getBoundingClientRect().height;
console.log(navHeight)
// Callback
const obsCallback = (entries, unobserver) => {
const [entry] = entries;
if (!entry.isIntersecting) stickyNav.classList.add("sticky-nav");
else stickyNav.classList.remove("sticky-nav");
}
// Option
const obsOption = {
root: null,
threshold: 0,
rootMargin: `-${navHeight}px`
}
const observer = new IntersectionObserver(obsCallback, obsOption);
window.onload = function(){
if(header != null) {
observer.observe(header);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment