As I scroll down, the header on my website remains in a static position and disappears. However, when I scroll back up, the header reappears wherever the user is on the page. While this functionality works well, I have noticed that as I scroll all the way to the top, my margins expand due to the header. Once it reaches the very top, the margin adjusts back to match the header's position.
In addition, there is banner image with an overlay on my site. If you scroll down and then back up, you will notice a change in margin caused by the image overlay. Additionally, the header appears 'fidgety' during this process.
How can I ensure that the margin always stays consistent and does not readjust?
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 {
if (st < navbarHeight) {
if (st === 0 || st < 1) {
$('header').css('position', 'static');
}
} else {
$('header').css('position', 'fixed');
}
// Scroll Up
if(st + $(window).height() < $(document).height()) {
$('header').removeClass('nav-up').addClass('nav-down');
}
}
lastScrollTop = st;
}
<header class="nav-down">
</header>
header {
background: #F2F2F2;
height: 120px;
top: 0;
transition: top 0.5s ease-in-out;
width: 100%;
z-index: 100;
border-bottom: 1px solid #9C9C9C;
}
.nav-up {
top: -123px;
}