Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically change Intersection Observer's configuration

I have a section on my page to which when user scrolls, an event fires. The solution uses IntersectionObserver which is perfect for my need. However, I would like to adapt the size of rootMargin of this observer, when the uses is already there.

Now the simplest approach when having an observer like this:

const options = { rootMargin: '20px' };
let observer = new IntersectionObserver(callback, options);

would be to assign the properties of it:

observer.rootMargin = '0px';

But is doesn't seem to work.

Is is possible and how to change the behaviour of once created Intersection Observer?

like image 823
wiktus239 Avatar asked Mar 27 '18 11:03

wiktus239


People also ask

What is rootMargin in intersection observer?

The IntersectionObserver interface's read-only rootMargin property is a string with syntax similar to that of the CSS margin property. 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.

Can intersection observer observe multiple elements?

observe() The IntersectionObserver method observe() adds an element to the set of target elements being watched by the IntersectionObserver . One observer has one set of thresholds and one root, but can watch multiple target elements for visibility changes in keeping with those.


Video Answer


1 Answers

You cannot, the properties are readonly.

interface IntersectionObserver {
  readonly attribute Element? root;
  readonly attribute DOMString rootMargin;
  readonly attribute FrozenArray<double> thresholds;
  ...

You should just replace your old observer with a new one. Maybe copy over the old options and just set what you need.

like image 182
H.B. Avatar answered Oct 17 '22 06:10

H.B.