The intersection observer.
Basic usage:
let ev = elementVisibility.inview(element);
// EV takes a moment to boot up so promise provided.
ev.readyPromise.then(())=> {
console.log(ev.state().inview); // Is the elmeent inview.
});
ev.dispose();
Basic usage with callback structure.
elementVisibility.inview(element, { threshold: 0.3 },
// Note that your callback will get immediately
// called once to check visibility
(element, changes, dispose)=> {
if(changes.isIntersecting) {
// The element is visibile.
dispose(); // Dispose if you want.
}
}
);
Element visibility internally caches the last known changes so you can use that in your app.
This is often an easier way to do things that use the callback.
let ev = elementVisibility.inview(element);
console.log(ev.state().inview); // Is the elmeent inview now?
window.setTimeout(()=> {
console.log(ev.state().inview); // Is it inview now after 3 seconds.
}, 3000);
window.addEventListener('scroll', () => {
console.log(ev.state().inview); // Check to see it is in view.
});
ev.state().changes; // A list of all known last changes.
Contains IntersectionObserverEntry list.
ev.state().lastChange; // Just the last known IntersectionObserverEntry.
ev.dispose(); // Remember to dispose.
--> I want to check if my element is inview just once.
let ev = elementVisibility.inview(element, {});
// This could be falsy since ev takes a moment to boot up.
ev.inview; // True or False.
// Instead
if(ev.state().ready) {
ev.inview; // True or False.
}
// Or
ev.readyPromise.then(()=> {
ev.inview; // True or False.
})
ev.dipose(); // Dispose it.
--> I want to run scroll events only when the element is inview. See DomWatcher for an example of this.