My navigation component includes a slim banner that should hide upon scroll and a main-nav bar that should stick to the top of the screen and shrink when it does so.
I initially looked into using Intersection Observer based on a popular answer found here: Event to detect when position:sticky is triggered
However, I encountered an issue where my child elements (which are flex) caused a flicker when transitioning between showing and hiding the sticky banner. Removing these child elements isn't an option, so I am considering applying position: fixed
to the main-nav
with top: 40px
. This setup allows the skinny-banner to scroll away as intended, but now I am seeking help in obtaining the scrollbar position via JavaScript. Once achieved, I plan to add a class like .isSticky
when the skinny-banner disappears to ensure that the main-nav sticks to the top.
.isSticky {
top: 0;
height: 66px;
}
body {
margin: 0;
height: 200vh;
}
.skinny-banner{
background: lightblue;
height: 40px;
display: flex;
}
.nav-menu {
display: flex;
}
.sticky-nav{
position: fixed;
top: 40px;
background: salmon;
transition: .1s;
}
/* styles for when the header is in sticky mode */
.sticky-nav.isSticky{
top: 0;
height: 66px;
}
<header>
<div class="skinny-banner">Skinny banner that on scroll down disapears.</div>
<div class="sticky-nav">Sticky Header that on scroll down sticks to top and shrinks in height when stuck</div>
</header>
I would like to develop a vanilla JS, HTML, & CSS solution while preserving the existing HTML structure which includes a wrapping container with the skinny-banner and nav-menu as children.