16 January, 2023
How to use Sticky navigation
Table of Content
A sticky navigation is a navigation that stays fixed to the top of the screen as the user scrolls down the page. Here’s an example of how you might implement a sticky navigation using HTML, CSS, and JavaScript:
HTML:
<div id="navbar">
<ul>
<li><a href="#section1">Section 1</a></li>
<li><a href="#section2">Section 2</a></li>
<li><a href="#section3">Section 3</a></li>
</ul>
</div>
CSS:
#navbar {
position: fixed; /* position element on top of the page */
top: 0; /* position element at the top of the page */
width: 100%; /* take up the full width of the page */
background-color: #fff; /* give the navbar a background color */
z-index: 1; /* ensure the navbar appears above other elements */
}
JavaScript:
window.onscroll = function() {stickyNavbar()};
// Get the navbar
var navbar = document.getElementById("navbar");
// Get the offset position of the navbar
var sticky = navbar.offsetTop;
// Add the sticky class to the navbar when you reach its scroll position. Remove "sticky" when you leave the scroll position
function stickyNavbar() {
if (window.pageYOffset >= sticky) {
navbar.classList.add("sticky")
} else {
navbar.classList.remove("sticky");
}
}
You can also use CSS position:sticky property instead of javascript. And you need to check browser support before using it.
#navbar {
position: -webkit-sticky; /* Safari */
position: sticky;
top: 0; /* position element at the top of the page */
width: 100%; /* take up the full width of the page */
background-color: #fff; /* give the navbar a background color */
z-index: 1; /* ensure the navbar appears above other elements */
}
You can also add some transition to make it look more smooth.
#navbar.sticky {
transition: top 0.5s;
}
You can customize the HTML, CSS and javascript according to your requirement.