Skip to content

Instantly share code, notes, and snippets.

@avcohen
Created June 4, 2021 03:16
Show Gist options
  • Save avcohen/534180434e35ebbdc65e0f1ef03fe554 to your computer and use it in GitHub Desktop.
Save avcohen/534180434e35ebbdc65e0f1ef03fe554 to your computer and use it in GitHub Desktop.
IO Nav
import $ from "jquery";
import { component } from "picoapp";
export default component((node) => {
const links = node.querySelectorAll("a");
const sections = document.querySelectorAll(".js-nav-section");
const rootMargin = `-45% 0px -45% 0px`;
const threshold = 0;
const observer = new IntersectionObserver(onIntersection, {
rootMargin,
threshold,
});
function updateActiveNavLinks(href) {
links.forEach((l) => {
if (href === l.getAttribute("href")) {
$(l).addClass("active");
} else {
$(l).removeClass("active");
}
});
}
function onIntersection(entries) {
entries.forEach((entry) => {
if (entry.isIntersecting) {
// Get ID from Section
let activeLink = entry.target.id;
// Set Active Link in Nav List
updateActiveNavLinks(`#${activeLink}`);
}
});
}
function initListeners() {
// Init Observer on Sections
sections.forEach((section) => observer.observe(section));
// Init Click Listeners on Links
links.forEach((link) => {
$(link).on("click", function (e) {
e.preventDefault();
// Get Section ID From Link
const target = $(this).attr("href");
if (target === "#") {
window.scrollTo({
top: 0,
behavior: "smooth",
});
return;
}
const scrollPosition =
$(target).height() < window.innerHeight
? $(target).offset().top - $(target).height()
: $(target).offset().top;
window.scrollTo({
top: scrollPosition,
behavior: "smooth",
});
});
});
}
initListeners();
});
<nav class="sticky-nav" data-component="stickyNav">
<ul>
<li>
<a class="link-hover" href="#">Top</a>
</li>
<li>
<a class="link-hover" href="#details">Details</a>
</li>
<li>
<a class="link-hover" href="#specifications">Specifications</a>
</li>
<li>
<a class="link-hover" href="#commitments">Commitments</a>
</li>
<li>
<a class="link-hover" href="#faq">FAQ</a>
</li>
</ul>
</nav>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment