I need to find a good solution to the following problem. I see a lot of people asking about tracking if an element is in or outside of view Port for the page or browser wind
Here is a pure javascript solution.
function elementIsVisible(element, container, partial) {
var contHeight = container.offsetHeight,
elemTop = offset(element).top - offset(container).top,
elemBottom = elemTop + element.offsetHeight;
return (elemTop >= 0 && elemBottom <= contHeight) ||
(partial && ((elemTop < 0 && elemBottom > 0 ) || (elemTop > 0 && elemTop <= contHeight)))
}
// checks window
function isWindow( obj ) {
return obj != null && obj === obj.window;
}
// returns corresponding window
function getWindow( elem ) {
return isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
}
// taken from jquery
// @returns {{top: number, left: number}}
function offset( elem ) {
var docElem, win,
box = { top: 0, left: 0 },
doc = elem && elem.ownerDocument;
docElem = doc.documentElement;
if ( typeof elem.getBoundingClientRect !== typeof undefined ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
top: box.top + win.pageYOffset - docElem.clientTop,
left: box.left + win.pageXOffset - docElem.clientLeft
};
};