DEV Community


Nav-link's to active as you scroll through sections, in 10 Lines of JavaScript;

Areeb ur Rub
18 | coding since 2016 | Arduino | Python | JavaScript | HTML/CSS | Love learn making things
・2 min read

Buy Me A Coffee

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.
Nav-bar Demo

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) => {
    if (li.classList.contains(current)) {

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)

Buy Me A Coffee
Follow Me for more:

areeburrub image

Discussion (0)