Class not becoming active upon scroll with js

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 class="scrollmenu">
    <li class="starters"><a href="#starters">STARTERS</a></li>
    <li class="ramen"><a href="#ramen">RAMEN</a></li>

starters should become active when you reach this section on the page:
<section id="starters" class="foodgrid">...</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) => {
    if (li.classList.contains(current)) {


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;

>Solution :

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

Leave a Reply