You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
<headerclass="header"><navclass="nav">
// ....
</nav></header>
// A section in the page
<sectionclass="section" id="section--1">
// ...
</section>
// Old way/* const section1 = document.querySelector('#section--1');const initialCoords = section1.getBoundingClientRect();console.log(initialCoords);// this works but it creates a lot of functionwindow.addEventListener('scroll', function () { console.log(window.scrollY); if (window.scrollY > initialCoords.top) nav.classList.add('sticky'); else nav.classList.remove('sticky');}); */// New way with Intersection Observer APIconstheader=document.querySelector('.header');constnavHeight=nav.getBoundingClientRect().height;conststickyNav=function(entries){const[entry]=entries;// equivalent to `const entry = entries[0]`// console.log(entry);if(!entry.isIntersecting)nav.classList.add('sticky');elsenav.classList.remove('sticky');};constheaderObserver=newIntersectionObserver(stickyNav,{root: null,threshold: 0,// percentage of intersection that the observer callback (`stickyNav`) will be calledrootMargin: `-${navHeight}px`,// stick the nav bar before it entering the content so that content doesn't get covered});headerObserver.observe(header);// More explanation for the `threshold`.// Is the threshold is 0.1 (10%), then everytime the `header` is overlapped (intersected) with// the viewport 10%, the callback (`stickyNav`) will be called.