Home > Back-end >  I'm trying to make my navbar fixed when the user scrolls down, but when I scroll down it doesn&
I'm trying to make my navbar fixed when the user scrolls down, but when I scroll down it doesn&

Time:06-06

I'm trying to make it so that when the user starts scrolling, the navbar becomes fixed at the top. I'm using vanilla javascript to add my fixed navbar class dynamically on a scroll event, and when I check the devtools the class is being added, but the navbar doesn't change, so I'm assuming the issue is with my CSS. Any help is appreciated.

const navbar = document.querySelector(".navbar");
// fixed navbar on scroll
window.addEventListener("scroll", () => {
  if (window.scrollY > 80) {
    navbar.classList.add(".navbar-fixed");
  } else {
    navbar.classList.remove(".navbar-fixed");
  }
});
.navbar-fixed {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background: white;
  color: black;
  z-index: 2;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.nav-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  max-width: 1100px;
  margin: 0 auto;
  padding: 0 30px;
  height: 100%;
}

.nav {
  list-style-type: none;
  display: flex;
  background: transparent;
}
<!-- NAVBAR -->
<div >
  <nav id="home" >
    <div >
      <div >Logo</div>
      <ul >
        <li>
          <a href="#home">Home</a>
        </li>
        <li>
          <a href="#about">About</a>
        </li>
        <li>
          <a href="#">Events</a>
        </li>
      </ul>
    </div>
  </nav>
  <div style="height: 1000px"></div>
</div>
<!-- END OF NAVBAR -->

CodePudding user response:

Pretty close, just remove the dot when you add and remove the classList of navbar:

const navbar = document.querySelector(".navbar");
  // fixed navbar on scroll
  window.addEventListener("scroll", () => {
  if (window.scrollY > 80) {
      navbar.classList.add("navbar-fixed");
  } else {
      navbar.classList.remove("navbar-fixed");
  }
});

CodePudding user response:

const navbar = document.querySelector("#home");
// fixed navbar on scroll
window.addEventListener("scroll", () => {
  if (window.scrollY > 80) {
    navbar.classList.add("navbar-fixed");
  } else {
    navbar.classList.remove("navbar-fixed");
  }
  
});
  • Related