Last active
August 29, 2015 14:06
-
-
Save Hotell/9372971227d052176240 to your computer and use it in GitHub Desktop.
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
var dom = (function(window) { | |
'use strict'; | |
var docElem = window.document.documentElement; | |
function getViewportSize() { | |
return { | |
w: Math.max(document.documentElement.clientWidth, window.innerWidth || 0), | |
h: Math.max(document.documentElement.clientHeight, window.innerHeight || 0) | |
} | |
} | |
function scrollY() { | |
return window.pageYOffset || docElem.scrollTop; | |
} | |
// http://stackoverflow.com/a/5598797/989439 | |
//finding element's position relative to the document | |
function getOffset(el) { | |
var offsetTop = 0, offsetLeft = 0; | |
do { | |
if ( !isNaN( el.offsetTop ) ) { | |
offsetTop += el.offsetTop; | |
} | |
if ( !isNaN( el.offsetLeft ) ) { | |
offsetLeft += el.offsetLeft; | |
} | |
} while( el = el.offsetParent ) | |
return { | |
top : offsetTop, | |
left : offsetLeft | |
} | |
} | |
function inViewport(el, h) { | |
var elH = el.offsetHeight, | |
scrolled = scrollY(), | |
viewed = scrolled + getViewportSize().h, | |
elTop = getOffset(el).top, | |
elBottom = elTop + elH, | |
// if 0, the element is considered in the viewport as soon as it enters. | |
// if 1, the element is considered in the viewport only when it's fully inside | |
// value in percentage (1 >= h >= 0) | |
h = h || 0; | |
return (elTop + elH * h) <= viewed && (elBottom) >= scrolled; | |
} | |
return { | |
viewportSize: getViewportSize, | |
scrollY: scrollY, | |
offset: getOffset, | |
isInViewport: inViewport | |
} | |
})(window); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment