JSFiddle - React, Tailwind, and code Playground
HTML
<div class="container">
<div class="before-content">This content should scroll off the screen</div>
<div class="sticky">Sticky content</div>
<div class="after-content">This is some extra content after</div>
</div>
CSS
.container {
background-color: #002b36;
}
* {
color: #b58900;
}
.before-content {
height: 50px;
}
.sticky {
height: 30px;
background-color: #073642;
position: sticky;
top: 10px;
}
.after-content {
height: 200px;
}
JavaScript
const sticky = document.getElementsByClassName("sticky")[0];
const observer = new IntersectionObserver(
([e]) => {
console.log(e.intersectionRatio)
const stuck = e.intersectionRatio < 1.0;
sticky.innerHTML = "Sticky content (" + String(stuck) + ")"
}, {
threshold: [1],
// This doesn't work; changing the css ".sticky { top : -1 }" does cause the intersect logic
// to fire and "stuck == true", but according to mdn docs it sounds like setting rootMargin
// this way should have the same effect.
rootMargin: '11px 0px 0px 0px',
}
)
observer.observe(sticky)