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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With