Skip to content

Instantly share code, notes, and snippets.

@jgatjens
Last active November 3, 2020 23:31
Show Gist options
  • Save jgatjens/fc091e61a86eb62a9020a8fa1e4b042e to your computer and use it in GitHub Desktop.
Save jgatjens/fc091e61a86eb62a9020a8fa1e4b042e to your computer and use it in GitHub Desktop.
Javascript scroll sticky navigation
// Example
// https://jsbin.com/kaviwuzeso/edit?css,output
const stickyNav = () => {
const nav = document.querySelector('.ni__pinned-nav--container');
const activeClass = 'is-active';
const navLinks = nav.querySelectorAll('a');
const sections = document.querySelectorAll('.pinned-nav--section');
if (!nav) return;
const offsetop = nav.offsetTop;
window.addEventListener('scroll', function(e) {
let fromTop = window.scrollY;
if (fromTop > offsetop) {
nav.classList.add('is-nav--sticky');
} else {
nav.classList.remove('is-nav--sticky');
}
navLinks.forEach(link => {
let section = document.querySelector(link.hash);
if (section.offsetTop <= fromTop && section.offsetTop + section.offsetHeight > fromTop) {
link.classList.add(activeClass);
} else {
link.classList.remove(activeClass);
}
});
});
nav.addEventListener('click', e => {
e.preventDefault();
if (e.target.tagName.toLowerCase() === 'a') {
const href = e.target.hash;
document.querySelector(href).scrollIntoView({
behavior: 'smooth'
});
}
});
};
.ex-pinned-nav--component {
height: 400px;
background-color: #e7e7e7;
}
.pinned-nav--section {
height: 400px;
background-color: azure;
}
.pinned-nav--section:nth-child(even) {
background-color: tomato;
}
.ni__pinned-nav--container {
width: 100%;
background-color: var(--white-three);
padding-top: 26px;
}
.ni__pinned-nav--container.is-nav--sticky {
position: fixed;
top: 0;
z-index: 100;
}
<section class="ex-pinned-nav--component"></section>
<div class="ni__pinned-nav--container">
<nav class="ni__pinned-nav">
<a class="ni__in-page-nav--1 is-active" href="#pinned-nav-systems">Systems</a>
<a class="ni__in-page-nav--1" href="#pinned-nav-hardware">Hardware</a>
<a class="ni__in-page-nav--1" href="#pinned-nav-software">Software</a>
<a class="ni__in-page-nav--1" href="#pinned-nav-services">Services</a>
</nav>
</div>
<section class="pinned-nav--section" id="pinned-nav-systems"></section>
<section class="pinned-nav--section" id="pinned-nav-hardware"></section>
<section class="pinned-nav--section" id="pinned-nav-software"></section>
<section class="pinned-nav--section" id="pinned-nav-services"></section>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment