I am currently working on a site product where I have to create a site-header that is always fixed on top of the viewport but when I scroll down it hides, and again when I scroll up, it becomes visible again. Actually, I made it happen somehow but I think the JQuery I used can be simpler and currently has some unnecessary variations in it. I used the JQuery from a reference available on internet.
Here is my code.
HTML
<header class="site-header">
<div class="inner">
</div>
</header>
CSS
.site-header {
position: fixed;
top: 0;
z-index: 1;
width: 100%;
height: 60px;
background: #fff;
transition: transform .25s;}
.hidden {transform:translateY(-100%)}
JQuery
jQuery( function( $ ) {
var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('.site-header').outerHeight();
$(window).scroll(function(event){
didScroll = true;
});
setInterval(function() {
if (didScroll) {
hasScrolled();
didScroll = false;
}
}, 250);
function hasScrolled() {
var st = $(this).scrollTop();
// Make scroll more than delta
if(Math.abs(lastScrollTop - st) <= delta)
return;
// If scrolled down and past the site-header, add class .hidden.
if (st > lastScrollTop && st > navbarHeight){
// Scroll Down
$('.site-header').addClass('hidden');
} else {
// Scroll Up
if(st + $(window).height() < $(document).height()) {
$('.site-header').removeClass('hidden');
}
}
lastScrollTop = st;
}
} );
Now, all these things together are functional and I have a header that is fixed; when I scroll down, it disappears and when I scroll back up, it becomes visible again - as I wanted. But, since I am not very familiar with JQuery, I am not sure whether this JQuery could be simpler. I think it would be great if I can achieve the same results with a smaller and simpler JQuery.