Looking at the IntersectionObserver API, it sounds like you can use rootMargin to specify offsets for the container to coerce the API to fire when an element is either near or some number of pixels inside a target container. But with the below example, it seems to not fire. I've set the 'rootMargin' to have an 11px top margin, so the sticky element (which sticks 10px from the top) should be partially overlapping, thus causing the observer to report a change in visibility.
This logic works fine if I have top: -1px instead of top: 10px, but from all the documentation I can find, this should work as well. I've tried a few variations of margins, negative values, etc to try to make this work, without success, but randomly guessing shouldn't be the solution.
Any idea what I'm doing wrong?
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:
* {
color: #b58900;
}
.container {
background-color: #002b36;
}
.before-content {
height: 50px;
}
.sticky {
height: 30px;
background-color: #073642;
position: sticky;
top: 10px;
}
.after-content {
height: 200px;
}
JS:
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)