Is there a way to make the Bootstrap navbar hide after scrolling for 300px?
I found a code snippet here that hides the navbar on scroll, but it hides immediately. How can I modify it to hide only after scrolling 300px?
HTML:
<nav class="autohide navbar navbar-expand-lg navbar-dark bg-primary">
<div class="container-fluid">
<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>
Javascript:
document.addEventListener("DOMContentLoaded", function(){
el_autohide = document.querySelector('.autohide');
// add padding-top to bady (if necessary)
navbar_height = document.querySelector('.navbar').offsetHeight;
document.body.style.paddingTop = navbar_height + 'px';
if(el_autohide){
var last_scroll_top = 0;
window.addEventListener('scroll', function() {
let scroll_top = window.scrollY;
if(scroll_top < last_scroll_top) {
el_autohide.classList.remove('scrolled-down');
el_autohide.classList.add('scrolled-up');
}
else {
el_autohide.classList.remove('scrolled-up');
el_autohide.classList.add('scrolled-down');
}
last_scroll_top = scroll_top;
});
// window.addEventListener
}
// if
});
// DOMContentLoaded end
CSS:
.scrolled-down{
transform:translateY(-100%); transition: all 0.3s ease-in-out;
}
.scrolled-up{
transform:translateY(0); transition: all 0.3s ease-in-out;
}