One issue I'm facing is with adding a class to my header. The goal is to reduce the height of the top part of the header when the user scrolls down and then remove the class when they scroll back up. While this functionality is working, there is an unexpected behavior where the class is added and removed continuously, most likely due to the continuous firing of the 'scroll' event triggered by the height change.
$(function() {
const $header = $('header');
let prevScroll = 0;
$(window).scroll(function() {
let scroll = $(window).scrollTop();
if (prevScroll - scroll > 0) {
$header.removeClass('scrolled-down');
} else {
$header.addClass('scrolled-down');
}
prevScroll = scroll;
});
});
.container {
position:relative;
width:90%;
margin:0 auto;
}
header {
position:sticky;
top:0;
}
.top-header {
background:blue;
height:50px;
transition:all .5s;
}
header.scrolled-down .top-header {
height:10px;
}
.nav-header {
background:red;
height:100px;
}
.body-content {
min-height:1500px;
border:1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<header>
<div class="top-header"></div>
<div class="nav-header"></div>
</header>
<div class="body-content"></div>
</div>