Skip to content

Instantly share code, notes, and snippets.

@and80506
Last active December 30, 2015 21:49
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 and80506/7890018 to your computer and use it in GitHub Desktop.
Save and80506/7890018 to your computer and use it in GitHub Desktop.
Check if element is visible on viewport
var isOnViewPort = (function() {
var compatMode = document.compatMode;
function posY(elm) {
var test = elm, top = 0;
while(!!test && test.tagName.toLowerCase() !== "body") {
top += test.offsetTop;
test = test.offsetParent;
}
return top;
}
function viewPortHeight() {
var de = document.documentElement;
if(!!window.innerWidth){
return window.innerHeight;
}else if(compatMode == 'CSS1Compat'){
return de.clientHeight;
}else if(compatMode == 'BackCompat'){
return document.body.clientHeight;
}
}
function scrollY() {
if( window.pageYOffset ) {
return window.pageYOffset;
}else if(compatMode == 'CSS1Compat'){
return document.documentElement.scrollTop;
}else if(compatMode == 'BackCompat'){
return document.body.scrollTop;
}
}
function _isOnViewPort( elm ) {
var vpH = viewPortHeight(), // Viewport Height
st = scrollY(), // Scroll Top
y = posY(elm);
return st < y && y - st < vpH;
}
return _isOnViewPort;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment