Scrollspy with ‘just JavaScript’

P1xt
P1xt
Apr 17 · 3 min read
Native JavaScript to implement ScrollSpy (change active menu based on scrolled location on page)

There are only really four things you need to know:

How to get some JavaScript loaded up when your page loads:

document.addEventListener('DOMContentLoaded', function(){
// the JavaScript you want to run after the page loads
}, false);

How to get the DOM elements you want to either change or check the position of:

const sections = document.querySelectorAll(".template__section");
const menu_links = document.querySelectorAll(".template__nav-item a");

How to check whether a DOM element you care about is in the currently viewable area of the browser window:

window.addEventListener("scroll", () => {
// check position and update nav
});
const current = sections.length - [...sections].reverse().findIndex((section) => window.scrollY >= section.offsetTop - sectionMargin ) - 1

How to add or remove a class from a DOM element:

const makeActive = (link) => menu_links[link].classList.add("active");const removeActive = (link) => menu_links[link].classList.remove("active");const removeAllActive = () => [...Array(sections.length).keys()].forEach((link) => removeActive(link));

P1xt’s Blog

Software Engineering, Guides for learning how to program, Short programming competitions

P1xt

Written by

P1xt

Software Engineer. Gamer. Geek.

P1xt’s Blog

Software Engineering, Guides for learning how to program, Short programming competitions