scrollnavwp-nav-menu-item

classList is only affect the first li in the ul despect the fact that all the elements where selected


classList is only affect the first li in the ul despect the fact that all the elements where selected.

document.addEventListener("scroll", function() {
  const headerChangejh = document.querySelector(".nav-link");
  if (window.scrollY > 0) {
    headerChangejh.classList.add("scrolledy");
  } else {
    headerChangejh.classList.remove("scrolledy");
  }
})
  .nav-link {
  font-size: 1.2rem;
  font-weight: 800;
  transition: 0.7s ease;
  color: black;
}

.nav-link:hover {
  color: red;
  .nav-link.scrolledy {
    color: #2196f3;
  }
<ul class="nav-menu">
  <li class="nav-item">
    <a href="#" class="nav-link">For Individual</a>
  </li>

  <li class="nav-item">
    <a href="#" class="nav-link">For Companies</a>
  </li>

  <li class="nav-item">
    <a href="#" class="nav-link">App</a>
  </li>

  <li class="nav-item">
    <a href="#" class="nav-link">Jobs</a>
  </li>

  <li class="nav-item">
    <a href="#" class="nav-link">Contact us</a>
  </li>

</ul>

the above code only changes the first li in the ul, while other remain unchange despite the fact that all the elements was selected


Solution

  • document.addEventListener("scroll", function() {
      const links = document.querySelectorAll(".nav-link");
      for (const l of links) l.classList.toggle('scrolledy', window.scrollY > 0);
    })
    .nav-link {
      font-size: 1.2rem;
      font-weight: 800;
      transition: color 0.7s ease;
      color: black;
      display: block;
      height: 75px;
      background-color: #eee;
      border: 1px solid #ddd;
    }
    
    .nav-link:nth-child(odd) {
      background-color: #fff;
    }
    
    .nav-link:hover {
      color: red;
    }
    
    .nav-link.scrolledy {
      color: #2196f3;
    }
    <ul class="nav-menu">
      <li class="nav-item">
        <a href="#" class="nav-link">For Individual</a>
      </li>
    
      <li class="nav-item">
        <a href="#" class="nav-link">For Companies</a>
      </li>
    
      <li class="nav-item">
        <a href="#" class="nav-link">App</a>
      </li>
    
      <li class="nav-item">
        <a href="#" class="nav-link">Jobs</a>
      </li>
    
      <li class="nav-item">
        <a href="#" class="nav-link">Contact us</a>
      </li>
    
    </ul>