Skip to content

Instantly share code, notes, and snippets.

@db
Created June 10, 2016 03:04
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 db/b31980fe0285252fc7b72407cf2a66b6 to your computer and use it in GitHub Desktop.
Save db/b31980fe0285252fc7b72407cf2a66b6 to your computer and use it in GitHub Desktop.
getPercentageOfElementAreaViewable
function getPercentageOfElementAreaViewable(el) {
var viewport = { width: window.innerWidth, height: window.innerHeight };
var rect = el.getBoundingClientRect();
var area = rect.width * rect.height;
var visibleHeight = rect.height;
var visibleWidth = rect.width;
// deduct amount out of viewport at top
if (rect.top < 0) visibleHeight += rect.top;
// deduct amount out of viewport at bottom
if (rect.bottom > viewport.height) visibleHeight -= (rect.bottom - viewport.height);
// deduct amount out of viewport at left
if (rect.left < 0) visibleWidth += rect.left;
// deduct amount out of viewport at right
if (rect.right > viewport.width) visibleWidth -= (rect.right - viewport.width);
// TODO: determin if there any elements intersecting over this one. if so by how much.
// calculate area percentage
var visibleArea = visibleWidth * visibleHeight;
var visiblePercentageArea = parseInt(((visibleArea / area) * 100), 10);
if (visiblePercentageArea<0) visiblePercentageArea = 0;
return visiblePercentageArea;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment