Nav-link's to active as you scroll through sections, in 10 Lines of JavaScript;
Areeb ur Rub
Posted on June 8, 2021
You must have seen single page websites which have different sections displaying different information, and when you scroll down to every section the navbar active link changes.
You might know that you can add links to each section in a navbar for single page websites by just simply using <a href="#sectionID">Section Name</a>
but this doesn't change the style of the nav-links to active.
to change the link style we can simply add a active
to the classList of link.
So first we have to check in which section we are in for that we are simple taking every section top offset and when the pages y offset is equal to it we are then taking it's id attribute and adding the active class to it's link
All this is done every time the page is scrolled.
window.onscroll = () => { var current = ""; sections.forEach((section) => { const sectionTop = section.offsetTop; if (pageYOffset >= sectionTop ) { current = section.getAttribute("id"); } }); navLi.forEach((li) => { li.classList.remove("active"); if (li.classList.contains(current)) { li.classList.add("active"); } }); };
More things,
if we do it in this way then it will keep the upper section link active until the lower one reach the top so to avoid this we can subtract some numbers so that it don't behave like that.
more things we can do is take the height of Section and use some subtract some of its part from the section top like this pageYOffset >= sectionTop - (sectionHeight /2)
Posted on June 8, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
June 8, 2021