Skip to content

Instantly share code, notes, and snippets.

@smitroshin
Last active May 24, 2020 13:42
Show Gist options
  • Save smitroshin/c3f41f90fd3afd85cf1818d6a5bf40b1 to your computer and use it in GitHub Desktop.
Save smitroshin/c3f41f90fd3afd85cf1818d6a5bf40b1 to your computer and use it in GitHub Desktop.
Check is element is visible in viewport
/**
* Source: https://gomakethings.com/how-to-test-if-an-element-is-in-the-viewport-with-vanilla-javascript/
* ! IS BUGGED: In some cases window.innerHeight is bigger than bounding.bottom
* even if element is fully visible.
* TODO: Needs to be improved.
*/
const isInViewport = (elem) => {
const bounding = elem.getBoundingClientRect();
return (
bounding.top >= 0 &&
bounding.left >= 0 &&
bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
bounding.right <= (window.innerWidth || document.documentElement.clientWidth)
);
};
/**
* Source: https://stackoverflow.com/questions/123999/how-can-i-tell-if-a-dom-element-is-visible-in-the-current-viewport
* Theoretically should return true for full entrance of element in viewport.
* ! IS BUGGED: (top + height) <= (window.pageYOffset + window.innerHeight) is not correct in some cases.
* TODO: Needs to be improved.
*/
const isInViewport = (el) => {
let top = el.offsetTop;
let left = el.offsetLeft;
const width = el.offsetWidth;
const height = el.offsetHeight;
while(el.offsetParent) {
el = el.offsetParent;
top += el.offsetTop;
left += el.offsetLeft;
}
return (
top >= window.pageYOffset &&
left >= window.pageXOffset &&
(top + height) <= (window.pageYOffset + window.innerHeight) &&
(left + width) <= (window.pageXOffset + window.innerWidth)
);
};
/**
* Source: https://stackoverflow.com/questions/123999/how-can-i-tell-if-a-dom-element-is-visible-in-the-current-viewport
* Theoretically should return true for partial entrance of element in viewport.
*/
const isInViewport = (el) => {
let top = el.offsetTop;
let left = el.offsetLeft;
const width = el.offsetWidth;
const height = el.offsetHeight;
while(el.offsetParent) {
el = el.offsetParent;
top += el.offsetTop;
left += el.offsetLeft;
}
return (
top < (window.pageYOffset + window.innerHeight) &&
left < (window.pageXOffset + window.innerWidth) &&
(top + height) > window.pageYOffset &&
(left + width) > window.pageXOffset
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment