Created
June 10, 2016 03:04
-
-
Save db/b31980fe0285252fc7b72407cf2a66b6 to your computer and use it in GitHub Desktop.
getPercentageOfElementAreaViewable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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