We would normally track if a DOM element is visible in the viewport or not to understand user behaviour or to operate on the elment based on visibilty (animation, ajax calls etc).
We would normally apply a function like below to detect if an element is visible in the viewport:
// From the specconstobserver=newIntersectionObserver(changes=>{for(constchangeofchanges){console.log(change.time);// Timestamp when the change occurredconsole.log(change.rootBounds);// Unclipped area of rootconsole.log(change.boundingClientRect);// target.boundingClientRect()console.log(change.intersectionRect);// boundingClientRect, clipped by its containing block ancestors, and intersected with rootBoundsconsole.log(change.intersectionRatio);// Ratio of intersectionRect area to boundingClientRect areaconsole.log(change.target);// the Element target}},{});// Watch for intersection.observer.observe(target);// Stop watching.observer.unobserve(target);// Stop observing.observer.disconnect();
Say, if we were to observe this element, #catBox for visiblity, we would end up with: