Hudri
Hudri

Reputation: 249

Can Intersection observer be used to calculate/trigger at specific offset top of target?

TL,DR:

I don't care how much of the target container is visible, I just want to know when the target container reaches a specific offset from top of the viewport (window). Should I stick with the good old scroll event or can this be done with Intersection observer?

Long story:

For a project I need to create a vertical scrolling parallax effect (as seen on this page, when viewed on large screens).

The parallax animation needs to detect when the target container reaches a specific offset from top of the viewport. And it needs to know the scroll direction.

I've found this question that explains how the visibilty percentage can be used to determine the scoll direction, which solves my 2nd problem.

So my question is: Can I use Intersection observer to trigger a callback when my target container reaches a specific offset from top of the viewport?

In pseudo-code, I'd need something like this:

var observer = new IntersectionObserver(offsetReached, {root: null});

function offsetReached(entries, observer) {
  entries.forEach(entry => {
    if (entry.offsetFromTop == '200px') {
      entry.target.classList.add('container--fixed');
    }
  });
}

observer.observe('.container');

Upvotes: 3

Views: 3561

Answers (2)

Erin
Erin

Reputation: 5835

Use the rootMargin option on the IntersectionObserver:

var observer = new IntersectionObserver(offsetReached, {rootMargin: '-200px'});

Each side of the rectangle represented by rootMargin is added to the corresponding side in the root element's bounding box before the intersection test is performed. (MDN Web Docs: Intersection)Observer.rootMargin)

Upvotes: 3

Mosè Raguzzini
Mosè Raguzzini

Reputation: 15851

Intersectionobserver's purpose is to detect when a portion of element becomes visible, if you want to watch for offSetthe best option is to use the old fashioned scroll event and getBoundingClientRect() on the element you need to watch on.

Upvotes: 1

Related Questions