Make bootstrap navbar fixed on scroll (sticky top)

 https://bootstrap-menu.com/detail-fixed-onscroll.html

There are multiple ways to fix navbar or header on top of page to stay always visible. In this example we illustrate how to add fixed-top class when page scolled. To see the difference between normal and fixed top navigation menu, just scroll. Keep in mind, This will work only for desktop screens. But still you can customize our code example.

Steps to make bootstrap nav fixed top after scroll
  • Create navbar on top of page
  • Now check if window scrolled window.addEventListener('scroll', function() { ... }
  • Check if scrolled more than x amount of px if (window.scrollY > 50) { ... }
  • Select navbar element and add function classList.add('fixed-top'); to fix on top
  • Remove class fixed-top when page scrolled back to top
Here are basic code snippets
<header>
<div class="bg-warning py-2">
Some top header info
</div>
<nav id="navbar_top" class="navbar navbar-expand-lg navbar-dark bg-primary">
<div class="container">
<a class="navbar-brand" href="#">Brand</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#main_nav">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="main_nav">
<ul class="navbar-nav ms-auto">
<li class="nav-item"><a class="nav-link" href="#"> Menu item </a></li>
<li class="nav-item"><a class="nav-link" href="#"> Menu item </a></li>
<li class="nav-item"><a class="nav-link" href="#"> Menu item </a></li>
</ul>
</div> <!-- navbar-collapse.// -->
</div> <!-- container-fluid.// -->
</nav>
</header>
view rawcode.html hosted with ❤ by GitHub
document.addEventListener("DOMContentLoaded", function(){
window.addEventListener('scroll', function() {
if (window.scrollY > 50) {
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';
}
});
});
// DOMContentLoaded end
view rawscript.js hosted with ❤ by GitHub


Another simple solution with CSS:

There is more simple way also to do that, just add class name sticky-top to your navbar. But keep in mind, your navbar element must be direct child of body. If you wrap your navbar with some other div it will not work.

Không có nhận xét nào:

Cold Turkey Blocker

 https://superuser.com/questions/1366153/how-to-get-rid-of-cold-turkey-website-blocker-get-around-the-block Very old question, but still wan...