Skip to content

Instantly share code, notes, and snippets.

@tcaptan-cr
Last active November 21, 2023 20:35
Show Gist options
  • Save tcaptan-cr/dfc5125c36655c69fb6d522db6ce355b to your computer and use it in GitHub Desktop.
Save tcaptan-cr/dfc5125c36655c69fb6d522db6ce355b to your computer and use it in GitHub Desktop.
Intersection Observer Scroll Margin Explainer

Intersection Observer Scroll Margin Explainer

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

Problem

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.

Proposed Solution

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.

Code Example

<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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment