js detect if element is in viewport code example
Example 1: javascript in viewport
var isInViewport = function (elem) {
var bounding = elem.getBoundingClientRect();
return (
bounding.top >= 0 &&
bounding.left >= 0 &&
bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
bounding.right <= (window.innerWidth || document.documentElement.clientWidth)
);
};
Example 2: how to check element is in viewport
function isVisible (ele) {
const { top, bottom } = ele.getBoundingClientRect();
const vHeight = (window.innerHeight || document.documentElement.clientHeight);
return (
(top > 0 || bottom > 0) &&
top < vHeight
);
}