I’ve already use this solution with IntersectionObserver (top:-1px
+ IntersectionObserver
), but it works only if target sticky element positioned as top:0 – in my case
I have two sticky elements with different top position and sticked together: How to do the same trick with sticky detection for nav element also?
// header sticky detection hack
const observer = new IntersectionObserver(
([e]) => e.target.classList.toggle("is-sticky", e.intersectionRatio < 1),
{
threshold: [1] }
);
observer.observe(document.querySelector('header'));
// how to do that with nav element?
body {
min-height: 200vh
}
.styled {
width: 100%;
text-align: center;
text-transform: uppercase;
display: flex;
justify-content: center;
align-items: center;
}
header {
background: #ccc;
height: 72px;
position: sticky;
top:-1px; /* trick */
}
header.is-sticky {
background: yellow;
}
.hero {
height: 400px;
background: #ddd;
width: 100%;
}
nav {
background: #bbb;
height: 36px;
position: sticky;
top:72px;
width: 100%;
}
nav.is-sticky {
background: green;
}
<header class="styled">HEADER</header>
<div class="hero styled">SOME CONTENT</div>
<nav class="styled">NAVIGATION</nav>