Intersection Observer when element leaves the viewport

Barry Horbal picture Barry Horbal · Nov 14, 2018 · Viewed 9.8k times · Source

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?

Answer

Pragun picture Pragun · Mar 15, 2019

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.