window.addEventListener("scroll", (event) => {
let fromTop = window.scrollY + 10;
mainNavLinks.forEach((link) => {
let section = document.querySelector(link.hash);
if (
section.offsetTop <= fromTop &&
section.offsetTop + section.offsetHeight > fromTop
) {
link.classList.add("active");
} else {
link.classList.remove("active");
}
});
});
It works like this:
hi webpage, if someone scrolls, do this => {
"fromTop" is how far someone scrolled from the top of the page (in px)
now go through all mainNavLinks, and for each link, do this => {
get me the section that belongs to this link (from link.hash)
if (
my current position is somewhere in the range of this section
) {
give this link a class "active"
} otherwise {
remove the class "active" from this link
}
}
}
1 Like
thankyou for such simple explaination…
You’re welcome, it’s impossible for me to guess how much you already know, since you only gave some code without context. Feel free to ask more specific questions.
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.