Here is a way to check if an element is currently visible in the viewport using JavaScript:
index.tsx622 chars22 lines
This method uses the getBoundingClientRect()
method to get the position and size of the element relative to the viewport. It then checks if the element is fully visible in the viewport by comparing its top, left, bottom, and right coordinates with the viewport's dimensions.
Alternatively, you can use the Intersection Observer API to detect when an element enters or exits the viewport. This method is usually more performant, especially for detecting changes in the element's visibility over time. Here is an example:
index.tsx379 chars13 lines
This method creates a new IntersectionObserver
object and attaches it to the element to observe. When the element intersects with the viewport, the intersectionRatio
property of the entry
object will be greater than zero. We can use this property to determine if the element is fully visible in the viewport or not.
gistlibby LogSnag