I've been battling with an issue for several days now and can't manage to arrive at a working solution.
The component is a header that includes a skinny-banner and a sticky-nav that are wrapped in a parent element (so component level properties can be passed to it).
I'm using vanilla HTML, CSS & Javascript only and have tried various commonly accepted solutions but to no avail.
Skinny banner: should hide on scroll down
Sticky nav: should stick to top (when skinny banner is hidden), always remain visible and increase in height (when skinny banner is hidden).
I've currently got an open bounty for a different approach, but thus far no suitable answers have been put forward: Using position sticky with child flex elements causes flicker so using position fixed and Javascript scrollbar position instead
The common approach uses sticky
but doesn't account for child elements using display: flex
.
In this snippet I am trying to use offsetTop
to add a fixed
class when the user scrolls away from the top of the viewport, but still not achieving the desired outcome.
var sticky = document.querySelector('.sticky-nav');
var origOffsetY = sticky.offsetTop;
function onScroll(e) {
window.scrollY >= origOffsetY
? sticky.classList.add('fixed')
: sticky.classList.remove('fixed');
}
body {
height: 100vh;
margin: 0;
}
.skinny-banner {
background-color: lightpink;
padding-top: 16px;
padding-bottom: 16px;
}
skinny-banner ul {
display: flex;
}
.sticky-nav {
background-color: lightblue;
padding-top: 32px;
padding-bottom: 32px;
}
.nav-content {
display: flex;
}
.fixed {
position: fixed;
top: 0;
}
<header>
<div class="skinny-banner">
Skinny banner should disapear on scroll down
<ul>
Nav items
</ul>
</div>
<div class="sticky-nav">
Sticky nav should stick to top and increase in height when skinny banner is
hidden
<div class="nav-content"></div>
</div>
</header>
Any advice would be really welcome!