Skip to content

Instantly share code, notes, and snippets.

@jjmu15
Created January 27, 2014 10:19
Show Gist options
  • Save jjmu15/8646226 to your computer and use it in GitHub Desktop.
Save jjmu15/8646226 to your computer and use it in GitHub Desktop.
check if element is in viewport - vanilla JS. Use by adding a “scroll” event listener to the window and then calling isInViewport().
// Determine if an element is in the visible viewport
function isInViewport(element) {
var rect = element.getBoundingClientRect();
var html = document.documentElement;
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || html.clientHeight) &&
rect.right <= (window.innerWidth || html.clientWidth)
);
}
The above function could be used by adding a “scroll” event listener to the window and then calling isInViewport().
@cedrickvstheworld
Copy link

Just wrote a similar version that only accounts for height, but returns true when any part of the element is in the viewport:

function isVisible (ele) {
  const { top, bottom } = ele.getBoundingClientRect();
  const vHeight = (window.innerHeight || document.documentElement.clientHeight);

  return (
    (top > 0 || bottom > 0) &&
    top < vHeight
  );
}

this is the one working as of now

@stealthman22
Copy link

Great work guys @jjmu15 and Tsimons@ Your snippets are amazing. I have been looking for something like this. Didn't want to import a library to solve just one problem

@Mooh07
Copy link

Mooh07 commented Apr 26, 2022

you are probably the greatest human being in my perspective now, thanks

@MarvinWagner-BSS
Copy link

MarvinWagner-BSS commented Jul 19, 2024

Thanks for sharing this inspiring piece of code. ;)

Here is an extended version that supports checking for full visibility in more specific areas.

function isInViewport(element, parentElement=null)
{
	var childRect = element.getBoundingClientRect();
	if (parentElement == null)
	{
		// check for full visibility in window area
		// (original version)
		var html = document.documentElement;
		return (
			childRect.top >= 0 &&
			childRect.left >= 0 &&
			childRect.bottom <= (window.innerHeight || html.clientHeight) &&
			childRect.right <= (window.innerWidth || html.clientWidth)
		);
	}
	else
	{
		// check for full visibility in a specific parent element's area
		// (for scrollable containers that don't fill the whole window)
		var parentRect = parentElement.getBoundingClientRect();
		return (
			childRect.top >= parentRect.top &&
			childRect.left >= parentRect.left &&
			childRect.bottom <= parentRect.bottom &&
			childRect.right <= parentRect.right
		);
	}
}

@MohammedMalleck
Copy link

MohammedMalleck commented Jul 19, 2024

why arent you guys using the
IntersectionObserver API in vanilla JS?

More about it here < https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API >

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment