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.