There are mainly two ways to check if an element is visible/hidden on the screen during scrolling:
- Listening to the window scroll event.
- Observing the element for visibility using Intersection Observer API.
Scroll events have a lot of performance issues.
The new way is using Intersection Observer API. Intersection Observer API makes it possible to know when an element enters or exits the browser viewport. This API is asynchronous
var observer = new IntersectionObserver(function(entries) {
if(entries[0].isIntersecting === true)
console.log('Element is fully visible in screen');
}, { threshold: [1] });
observer.observe(document.querySelector("#element"));
Threshold is a number between 0 and 1, that represents the viewable area of the target element in the screen. For example, 0 represents no area of element is visible. A value of 0.10 represents about 10% area is viewable in the screen. Value of 1 means element is fully viewable in the screen.