simone
simone

Reputation: 5227

Can I use IntersectionObserver to detect where an element is with respect to bottom of window?

Right now I manage lazy loading of images when an element at the bottom of the screen becomes visible, like so:

let options = { rootMargin: '0px', threshold: 0.1 }
let callback = (entries, observer) => {
    console.log(entries[0]);
    var bar = entries[0];
    
    if (entries.filter(entry => entry.isIntersecting).length) {
         // load images    
    }
};
let observer = new IntersectionObserver(callback, options);
observer.observe(document.querySelector('#bottombar'))

This however means that the new images get loaded only when the bottom is reached, which gives a hiccup-y feel to the interaction.

Is it possible to fire the event when - for example - the element is a full screen height (or less) below the bottom of the screen? I guess it could be done with scroll events - but IntersectionObserver seems cleaner (and fires less often).

Upvotes: 2

Views: 2001

Answers (1)

Santiago V.
Santiago V.

Reputation: 1118

Yes you can.

Check this out: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API#creating_an_intersection_observer

You can create an IntersectionObserver and provide a custom root property which corresponds to an element bigger than the viewport (e.g. height: 200vh).

Also: if you provide a threshold of 0 you shouldn't have the hiccups you describe.

Another thing you can do is set a rootMargin of 100% to indicate that the margin is a whole new viewport.

Upvotes: 1

Related Questions