How to create fixed navbar on scoll in Bootstrap 5

November 08, 2023


Today we can learn how to create Sticky/Fixed Navbar on Scroll in Bootstrap 5.

Here is the navarbar code snippets.


<nav id="navbar_top" class="navbar navbar-expand-lg">
<div class="container">
<a class="navbar-brand" href="/"><img src="assets/images/logo.png" ></a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"><span class="navbar-toggler-icon"></span></button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ms-auto">
<li class="nav-item mx-2"><a class="nav-link" href="">Home</a></li>
<li class="nav-item mx-2"><a class="nav-link" href="">About Us</a></li>
<li class="nav-item mx-2"><a class="nav-link" href="">Products</a></li>
<li class="nav-item mx-1"><a class="nav-link" href="">Contact Us</a></li>
</ul>
</div>
</div>
</nav>


    Add the below code in in your stylesheet.


.fixed-top {
top: -40px;
transform: translateY(40px);
transition: transform .3s;
}


Add the code in your Javascript file or add it in header.

<script type="text/javascript"></script>
document.addEventListener("DOMContentLoaded", function(){
window.addEventListener('scroll', function() {
if (window.scrollY > 200) {
document.getElementById('navbar_top').classList.add('fixed-top');
// add padding top to show content behind navbar
navbar_height = document.querySelector('.navbar').offsetHeight;
document.body.style.paddingTop = navbar_height + 'px';
} else {
document.getElementById('navbar_top').classList.remove('fixed-top');
// remove padding top from body
document.body.style.paddingTop = '0';
}
});
});
</script>

No comments:

Powered by Blogger.