Intersection Observer scrollMargin allows developers to observe targets inside nested scroll containers that are currently clipped away by the scroll containers. This is achieved by expanding the container's clipping rect by the scrollMargin when calculating the intersection.
Intersection Observer Scroll Margin Specification
Developers would like to get intersection notifications when elements inside possibly nested scroll containers are near the viewport.
A good example of this use case would be lazy loaded images in carousels.
Without scrollMargin
developlers can only use rootMargin
and the intersection would only get reported
when the elements are at least partially visible because the root is the top-level viewport, not the scroll container,
causing the images to load later than anticipated.
Add a scrollMargin
option to the Intersection Observer API that will allow elements in scroll container
to be observed when near the viewport as expected.
With scrollMargin
, developers can cause carousel images to be loaded when they are near the viewport.
<style>
#scroller {
width: 100px;
height: 100px;
overflow: scroll;
background-color: gray;
}
#spacer {
width: 50px;
height: 100px;
}
#target {
width: 50px;
height: 50px;
background-color: green;
}
</style>
<div id=scroller>
<div id=spacer></div>
<div id=target></div>
</div>
<script>
let callback = (entries, observer) => {
console.log(entries);
}
const observer = new IntersectionObserver(
callback,
{
scrollMargin: "10px"
}
);
observer.observe(target);
</script>