Could we help you? Please click the banners. We are young and desperately need the money
Do you need to check if an element is on screen? If so, we have a simple-to-use function ready that allows you to do so.
/**
* Tests whether an element is present on screen.
*
* Returns true if the given element is on screen and false if not.
*
* @param {HTMLElement} elem The element whose presence is to test for.
* @param {Boolean} allowElemBehind If enabled, return true even if the element is behind of the screen area.
* @param {Boolean} allowElemAhead If enabled, return true even if the element is ahead of the screen area.
* @returns {Boolean}
*/
function onScreen(elem, allowElemBehind = false, allowElemAhead = false) {
const scrollDist = document.documentElement.scrollTop;
const elemOffset = window.scrollY + elem.getBoundingClientRect().top;
if (!allowElemBehind && !(elemOffset + elem.offsetHeight > scrollDist))
return false;
if (!allowElemAhead && !(scrollDist + window.innerHeight > elemOffset))
return false;
return true;
}
The "onScreen" function returns true if the element is on screen and false if not. It takes three parameters:
Syntax:
onScreen(elem, allowElemBehind = false, allowElemAhead = false); // returns either true or false
Example:
onScreen(document.getElementById('foo')); // tests if the element with the id of 'foo' is on screen