Ignacio Palma Balboa Ignacio Palma Balboa - 1 month ago 20
CSS Question

Sticky navigation with Javascript

I am doing a sticky nav but when i scroll fast it doesn´t work.. only when i scroll slowly would work but not always..

Here is the CSS:

div.sticky {
position: fixed;
}


and the Javascript:

window.addEventListener("scroll", function() {
var nav = document.getElementsByClassName("nav_lista")[0];
if(window.scrollY > 200) {
nav.className += " " + "sticky";
nav.style.top = 0;
} else if (window.scrollY < 200) {
nav.classList.remove("sticky");
nav.style.top = null;
}
});


Any idea where the bug can be?

Thanks!

Answer

I saw the following issues with your code:

  1. You don't handle the case in which window.scrollY is exactly equal to 200.
  2. You're setting style.top in js when you can do this all in the css.
  3. You're using className += instead of classList.add().

I addressed all of the above, and it works, as shown below:

window.addEventListener("scroll", function() {
  var nav = document.getElementsByTagName("nav")[0];
  nav.classList.toggle("sticky", window.scrollY > 200);
});
body {
  margin: 0;
}
nav {
  width: 100%;
  height: 200px;
  background-color: #99FFFF;
}
nav.sticky {
  position: fixed;
  top: 0;
}
main {
  background-color: #FF99FF;
  height: 200vh;
}
<nav>This is the nav</nav>
<main>This is the content</main>