🪴 yshalsager's Digital Garden

Search

Search IconIcon to open search

JavaScript Sticky Navigation bar

Last updated Jun 29, 2022

المعرفة:: JavaScript
الحالة:: #ملاحظة_مؤرشفة
المراجع:: The Complete JavaScript Course 2022 From Zero to Expert


1
2
3
4
5
<header>  
  <nav class="nav">...</nav>  
</header>  
  
<section class="section" id="section--1">  
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
/* NAVIGATION */  
.nav {  
  display: flex;  
  justify-content: space-between;  
  align-items: center;  
  height: 9rem;  
  width: 100%;  
  padding: 0 6rem;  
  z-index: 100;  
}  
  
/* nav and stickly class at the same time */  
.nav.sticky {  
  position: fixed;  
  background-color: rgba(255, 255, 255, 0.95);  
}  

# Classic Way

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const section1 = document.querySelector('#section--1');  
const nav = document.querySelector('.nav');  
  
const initialCoords = section1.getBoundingClientRect();  
console.log(initialCoords);  
window.addEventListener('scroll', function () {  
  console.log(window.scrollY);  
  if (window.scrollY > initialCoords.top) nav.classList.add('sticky');  
  else nav.classList.remove('sticky');  
});  

# Using Intersection Observer API

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
// Sticky navigation: Intersection Observer API  
const header = document.querySelector('.header');  
const navHeight = nav.getBoundingClientRect().height;  
  
const stickyNav = function (entries) {  
  // const entry = entries[0];  
  const [entry] = entries;  
  // console.log(entry);  
  
  if (!entry.isIntersecting) nav.classList.add('sticky');  
  else nav.classList.remove('sticky');  
};  
  
const headerObserver = new IntersectionObserver(stickyNav, {  
  root: null,  
  threshold: 0,  
  // rootMargin: `-90px`,  
  rootMargin: `-${navHeight}px`,  
});  
  
headerObserver.observe(header);