Skip to content

Instantly share code, notes, and snippets.

@chekit
Created January 14, 2016 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chekit/5b4346248ddd83925c6e to your computer and use it in GitHub Desktop.
Save chekit/5b4346248ddd83925c6e to your computer and use it in GitHub Desktop.
Detect if element inside viewport or not
function elementInViewport (el) {
var top = el.offsetTop;
var left = el.offsetLeft;
var width = el.offsetWidth;
var height = el.offsetHeight;
while(el.offsetParent) {
el = el.offsetParent;
top += el.offsetTop;
left += el.offsetLeft;
}
return (
top < (window.pageYOffset + window.innerHeight) &&
left < (window.pageXOffset + window.innerWidth) &&
(top + height) > window.pageYOffset &&
(left + width) > window.pageXOffset
);
}
//Source: http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment