8

The code for setting the rootMargin is shown below.

let observerOptions = {
    root: null,
    rootMargin: "100px",
    threshold: []
};

When I set it to 100px, the root element's bounding box isn't growing 100px; when I set it to -100px, the root element's bounding box isn't shrinking 100px.

Here is an example on jsFiddle. The example is taken directly from MDN's documentation of IntersectionObserver, and I only changed the value of rootMargin.

Ian Y.
  • 2,293
  • 6
  • 39
  • 55
  • 1
    I'm having a same issue here. Will post if I find update. – Ganapati V S Jul 26 '19 at 14:34
  • i didn't realise rootMargin was for the margin for the root, not for the element being observed. It makes sense, since the viewport is a scrollable area in the screen. – Rusty Rob Sep 02 '22 at 00:34

1 Answers1

24

In your example on jsFiddle, your IntersectionObserver is in a iframe (jsFiddle wrap all the code in a iframe). For works in a iframe you must set the root with the iframe element.

In general, rootMargin works well if you set the root element with the correct element (the element with the scrollbar). Eg.:

let observerOptions = {
    root: document.getElementById("parentScroll"),
    rootMargin: "100px",
    threshold: []
};

Try your code in a classic html file and probably it works with root: null, but it will never works on jsFiddle.

ar099968
  • 6,963
  • 12
  • 64
  • 127