Home > Mobile >  Class not becoming active upon scroll with js
Class not becoming active upon scroll with js

Time:12-30

I'm trying to make it so that when you scroll on my HTML page when you reach a certain section, that respective section should become active,

for example:

<nav >
  <ul>
    <li ><a href="#starters">STARTERS</a></li>
    <li ><a href="#ramen">RAMEN</a></li>
 </ul>
</nav>

starters should become active when you reach this section on the page: <section id="starters" >...</section>

I'm trying to do this with this JS code:

const sections = document.querySelectorAll("section");
const navLi = document.querySelectorAll("nav ul li");

window.addEventListener("scroll", () => {
  let current = " ";
  sections.forEach((section) => {
    const sectionTop = section.offsetTop;
    const sectionHeight = section.clientHeight;
    if (scrollY >= sectionTop) {
      current = section.getAttribute("id");
    }
  });

  navLi.forEach((li) => {
    li.classList.remove("active");
    if (li.classList.contains(current)) {
      li.classList.add("active");
    }
  });

});

I'm still going to expand on this JS code to make it work better but if I'm not mistaken it should already make the class visually active when I'm on the right section.

In case you are wondering my CSS looks like this for the time being:

nav ul li:active {
  background-color: blue;
}

CodePudding user response:

what happens here is that you are attaching a class name which is active and you are not declaring that class, you just have the event :active that is triggered when you click on the element, so you must do this

.active {
  background-color: blue;
}

and that will work when you set the class and remove it, also leaving the css code as you have it will make that when the html li element is clicked it changes it background and then changes to the normal color, try it and let me know if it works, if it doesn't is something about your js and then ill check it

  • Related