Simplest Sticky Header Nav In JavaScript

Category: Javascript , Menu & Navigation | December 8, 2020
Views Total:1,768 views
Official Page:Go to website
Last Update:December 8, 2020


Simplest Sticky Header Nav In JavaScript


A modern header navigation bar that sticks to the top of the webpage by using the CSS position: sticky property.

How to use it:

1. Create a header navbar from a nav list.

      <li class="nav__links"><a href="#">Home</a></li>
      <li class="nav__links"><a href="#">About</a></li>
      <li class="nav__links"><a href="#">Services</a></li>

2. Make the header navbar fixed on the top the page.

header {
  position: sticky;
  /* more styles here */

3. Listen for the scroll event and apply a Sticky class to the header navbar after the document is currently scrolled vertically from the origin.

window.addEventListener("scroll" ,function() {
  let header = document.querySelector("header");
  header.classList.toggle("sticky", window.scrollY > 0);

4. Change the styles of the header navbar when getting stuck.

.sticky {
  background: #fff;
  transition: 2s;
.sticky a {
  color: #5c4e82

You Might Be Interested In:

Leave a Reply