Is there a way to detect if an element leaves the viewport using Intersection Observers? For example, I have an element on the screen that I want to fire a callback when the top of the element hits the top of the viewport. From MDN:
The Intersection Observer API lets code register a callback function that is executed whenever an element they wish to monitor enters or exits another element (or the viewport), or when the amount by which the two intersect changes by a requested amount. -- (https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API)
So if I do something like below, I would have thought that the callback would have fired when the top of the element hit the top of the viewport as well?
var options = {
root: document.querySelector('#element'),
rootMargin: '0px',
threshold: 0
}
var observer = new IntersectionObserver(callback, options);
But it only seems to be firing when the top of the element scrolls in and hits the bottom of the viewport, but not both. Ideas?
The Intersection Observer API lets code register a callback function that is executed whenever an element they wish to monitor enters or exits another element (or the viewport), or when the amount by which the two intersect changes by a requested amount.
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.
The IntersectionObserver method unobserve() instructs the IntersectionObserver to stop observing the specified target element.
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.
If I correctly understand what you're trying to do, you could set rootMargin
to '0px 0px -100%'
. Also, threshold: 0
is the default, so you don't need to include it in your options object.
If you go through the API doc here, the threshold
option can be passed as an array to define on what levels of intersection should the callback be fired. So, passing something like [0, 0.8]
fires the callback each time the element is visible by at least 80% and also when the element is not visible (exits the viewport).
There might be other complications while doing this. For e.g. if there are multiple elements, whenever one element is visible, other element might exit the viewport hence firing unnecessary callbacks. I handled it using some additional if
conditions in my case. I also had to do some hit and trials to determine the best suitable values of threshold
and intersectionRatio
.
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