I have a header that disappears when the user scrolls down, and reappears when the user scrolls up. I was successful in getting the header to reappear with a slow transition, but I am unable to implement the same transition when it disappears. instead it disappears instantly which is not the intended function. I want it to have a 0.5s ease-in-out transition when disappearing like it does when it reappears. Could someone please help me create the desired effect?
////Header scroll effect//////
// Hide Header on on scroll down
var didScroll;
var lastScrollTop = 0;
var delta = 10;
var navbarHeight = $('header').outerHeight();
$(window).scroll(function(){
didScroll = true;
});
setInterval(function() {
if (didScroll) {
hasScrolled();
didScroll = false;
}
}, 250);
function hasScrolled() {
var st = $(this).scrollTop();
// Make sure user scroll more than delta
if(Math.abs(lastScrollTop - st) <= delta)
return;
// If user scrolled down and are past the navbar, add class .nav_up.
if (st > lastScrollTop && st > navbarHeight){
// Scroll Down Disappear
$('header').removeClass('header__top').addClass('nav_up');
$('label').removeClass('menu__btn').addClass('nav_up');
} else {
// Scroll Up Reappear
if(st + $(window).height() < $(document).height()) {
$('header').removeClass('nav_up').addClass('header__top');
$('label').removeClass('nav_up').addClass('menu__btn');
}
}
lastScrollTop = st;
}
body{
height: 30000px;
background-color: lightblue;
color: white;
}
.header__top {
width: 100%;
height: 120px;
background-color: #000;
position: fixed;
top: 0px;
z-index: 5;
border-bottom: 0.02rem solid #000 ;
display: flex;
box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px;
transition: top 0.5s ease-in-out;
}
.nav_up { /*---scroll up effect---*/
top: -120px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<header class="header__top">
<p>header</p>
</header>
</body>
2
Answers
I’ve updated a demo from w3schools. Made the transition property stay for the element using a different class. Scroll up/down detection copied from chatGPT.
As you remove the class
header__top
from element it also removes the transition properties. To avoid that you can add the target class and then remove the old class as a callback function: