How to Check If Element is Visible / Hidden in Page using Intersection Observer

javascript
Published on May 14, 2020

Checking whether an element is visible or hidden in page, even through it may not be in screen view, can be done through an Intersection Observer. The trick is to set IntersectionObserver's root element to document.documentElement.

document.documentElement refers to the root <html> element of the document. This means that intersection of the required element can be calculated with respect to the full page.

var observer = new IntersectionObserver(function(entries) {
	if(entries[0]['intersectionRatio'] == 0) {
		// element is hidden
	}
	else {
		// element is visible
		// entries[0]['intersectionRatio'] can be used to check whether element is visible fully or partially
	}
}, { root: document.documentElement });

// element to observe
observer.observe(document.querySelector("#footer"));
  • Intersection Observers work asynchronously, so it cannot be immediately known whether the element is visible or hidden. It will take a few milliseconds for the callback to be executed.

  • The default threshold of [0] is being used, so the callback will be executed if element gets completely hidden or partially visible (even by a few pixels). This means that the callback is guaranteed to be called when code is executed.

  • After knowing that element is visible or hidden, we may want to stop observing it. The unobserve() method can be called in the callback to do so.

    observer.unobserve()
  • Intersection Observer is the most performance oriented way to detect element visibility in page as it works asynchronously, and does not involve layout calculations.

Related Tutorials
How to Know when an Element Gets Visible in the Screen During Scrolling
Javascript Intersection Observer API Explained in Detail
Comments
Loading Comments