Here’s the interesting thing. If you create an Intersection Observer on the browser’s window, you can still observe elements inside a scrollable element.
You can specify rootMargin for top, right, bottom, and left directions. You do this with CSS’s margin shorthand.
// Sets all four sides to -150px
{ rootMargin: "-150px" }
// Sets top & bottom to -150px, left and right to -75px
{ rootMargin: "-150px -75px" }
// Sets top to -150px left and right to -75px, bottom to -50px
{ rootMargin: "-150px -75px -50px" }
// Sets top to -150px; right to -75px, bottom to -50px, left to -25px
{ rootMargin: "-150px -75px -50px -25px" }
Threshold
Threshold logs an entry when a specific % of the element is visible. It’s a number that ranges from 0 to 1.
0: Creates an entry when 0% mark of the observed element intersects the root. This is the default value.
1: Creates an entry when 100% of the observed element intersects the root.
Pay attention to the difference between threshold: 0 and threshold: 1.
threshold:0:
Entry created when top of element reaches bottom of root
Entry created when bottom of element reaches top of root
threshold: 1:
Entry created when bottom of element crosses bottom of root
Entry created when top of element crosses top of root
You can set threshold to an array. This creates an entry when the observed element crosses each threshold.
const observer = new IntersectionObserver(callback, {
threshold: [0,1]
})
threshold [0, 1]:
Entry created when top of element reaches bottom of root
Entry created when bottom of element reaches top of root
Entry created when bottom of element crosses bottom of root
Entry created when top of element crosses top of root
Entry properties
The remaining 2 entry properties would make sense now:
rootBounds: The root element’s boundingClientRect (which is determined by root and rootMargin.
intersectionRect Area where the boundingClientRect and rootBounds overlap.
Exercise
For rootMargin:
Set rootMargin to the following values. Observe when entries trigger.
0px
150px
-150px
For threshold
Set threshold to the following values. Observe when entries trigger.