Reputation: 1992
I have a fixed position navbar on my blog and I'm trying to implement simple JS to hide the navbar when scrolling down. The navbar will then reappear when scrolling up. The fiddle for the code I'm trying to implement here: https://jsfiddle.net/mariusc23/s6mLJ/31/
For some reason I'm running into issues and I hit a wall. Here is my code if anybody would like to help. Could the issue be the responsive version of my navbar? Any clues appreciated.
// Hide Header on on scroll down
var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('header').outerHeight();
$(window).scroll(function(event){
didScroll = true;
});
setInterval(function() {
if (didScroll) {
hasScrolled();
didScroll = false;
}
}, 250);
function hasScrolled() {
var st = $(this).scrollTop();
// Make sure they scroll more than delta
if(Math.abs(lastScrollTop - st) <= delta)
return;
// If they scrolled down and are past the navbar, add class .nav-up.
// This is necessary so you never see what is "behind" the navbar.
if (st > lastScrollTop && st > navbarHeight){
// Scroll Down
$('header').removeClass('nav-down').addClass('nav-up');
} else {
// Scroll Up
if(st + $(window).height() < $(document).height()) {
$('header').removeClass('nav-up').addClass('nav-down');
}
}
lastScrollTop = st;
}
.nav-up {
top: -40px;
}
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">
<script src="/javascript/navhider.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<!--NAVBAR-->
<aside id="shadow" class="nav-down">
<div id="navbar">
<nav>
<ul>
<li class="noselect"><a href="/">Home</a></li>
<li class="noselect"><a class="navlink" href="{{ "/contact" | prepend: site.baseurl }}">Contact</a></li>
<li class="noselect"><a class="navlink" href="{{ "/portfolio" | prepend: site.baseurl }}">Portfolio</a></li>
<li class="noselect"><a class="navlink" href="https://github.com/joelbitar1986">Github</a></li>
<li class="noselect"><a class="navlink" href="{{ "/blog" | prepend: site.baseurl }}">Blog</a></li>
</ul>
<div class="handle"><a id="menu-icon">☰</a></div><!--On a mobile device this is the only list item displaying -->
</nav>
</div>
</aside>
Upvotes: 1
Views: 216
Reputation: 1992
I was able to succeed in what I wanted to do by adding this script to index.html. I also got the original fiddle to work by replacing 'header' with 'aside' from my own code. Patience pays off!
<script type="text/javascript">
(function() {
var documentElem = $(document),
aside = $('aside'),
lastScrollTop = 0;
documentElem.on('scroll', function() {
var currentScrollTop = $(this).scrollTop();
//scroll down
if (currentScrollTop > lastScrollTop ) aside.addClass('hidden');
//scroll up
else aside.removeClass('hidden');
lastScrollTop = currentScrollTop;
});
})();
</script>
Upvotes: 1