Skip to content

Instantly share code, notes, and snippets.

@vosidiy
Created December 12, 2019 15:55
Show Gist options
  • Save vosidiy/0174455f77d380e0068fc2a3e0ebbef7 to your computer and use it in GitHub Desktop.
Save vosidiy/0174455f77d380e0068fc2a3e0ebbef7 to your computer and use it in GitHub Desktop.
Smart scroll
<nav class="navbar smart-scroll navbar-expand-lg navbar-dark bg-primary">
<a class="navbar-brand" href="#">Brand</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#main_nav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="main_nav">
<ul class="navbar-nav">
<li class="nav-item active"> <a class="nav-link" href="#">Home </a> </li>
<li class="nav-item"><a class="nav-link" href="#"> About </a></li>
<li class="nav-item"><a class="nav-link" href="#"> Services </a></li>
</ul>
</div> <!-- navbar-collapse.// -->
</nav>
// add padding top to show content behind navbar
$('body').css('padding-top', $('.navbar').outerHeight() + 'px')
// detect scroll top or down
if ($('.smart-scroll').length > 0) { // check if element exists
var last_scroll_top = 0;
$(window).on('scroll', function() {
scroll_top = $(this).scrollTop();
if(scroll_top < last_scroll_top) {
$('.smart-scroll').removeClass('scrolled-down').addClass('scrolled-up');
}
else {
$('.smart-scroll').removeClass('scrolled-up').addClass('scrolled-down');
}
last_scroll_top = scroll_top;
});
}
.smart-scroll{
position: fixed;
top: 0;
right: 0;
left: 0;
z-index: 1030;
}
.scrolled-down{
transform:translateY(-100%); transition: all 0.3s ease-in-out;
}
.scrolled-up{
transform:translateY(0); transition: all 0.3s ease-in-out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment