MenusLesson 35Free preview
Sticky Navbar
This lesson is part of How To · All levels
Summary
This lesson reviews the creation of Sticky Navbars using JavaScript and CSS. The navbar was originally under the hero header banner, and then as the user scrolled the page until the navbar touched the top edge of the screen, JavaScript inserted the .sticky class so that the locked menu bar would stick on top.
Key points
- Calculates the offsetTop navbar when the page is loaded (navbar.offsetTop)
- Listen to the event scroll to compare window.pageYOffset with the initial offsetTop
- Add the .sticky class (position: fixed; top: 0; width: 100%) when scrolling past the starting position
- It can be implemented purely with modern CSS using position: sticky; top: 0;
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.