Fixed or Sticky Navbar on scroll

/ July 23, 2021 / Front-End, JavaScript
Fixed sticky navbar on scroll

Hello, I have been working on the E-Learning platform for a while now. On the course description page, there is a Nav right after the course brief info. The requirement is to navigate those sections with the nav fixed to the top of the screen, It’s a good user experience though.

I had very little time, so I went through StackOverflow for a solution. Well, Immediately I got it. Just copy-pasted and it worked! Pushed to dev server as well.

Before going to production I cross-check code to understand better, I observed I had copy-pasted 12-15 lines of code for stick navbar functionality. After taking some time to understand I realized that it’s just a single line of code.

The solution

The solution is simple. Take the offsetTop of the navbar and check if it’s greater than scrollY(from the window object). If it’s true, add fixed-nav class to the navbar else remove it. Simple right?

JavaScript Code

<script>
     let navbar = document.getElementById("nav-section");
     let navOffset = navbar.offsetTop;
     window.addEventListener("scroll", () => {
         (window.scrollY >= navOffset) ? 
             navbar.classList.add("fixed-nav") : 
             navbar.classList.remove("fixed-nav")
     });
</script>

View the codepen

See the Pen Sticky header on scroll by KiranWorkspace (@kiranworkspace) on CodePen.


Related Post

How to make Ellipsis to multiline text in CSS
Showing 1 or 2 lines of the title looks good on designs like card or excerpt, also important to handle…

CSS, Front-End / December 31, 2020

How to stick footer to bottom of page if not enough content
Keeping header at top and footer at bottom is a common practice for almost all websites. Sometimes, if content is…

Front-End / December 31, 2020