Menü schliessen
Created: May 4th 2021
Last updated: March 8th 2024
Categories: JavaScript Development
Author: Tim Fürer

JavaScript: Check if an element is on screen

Tags:  HTML,  Javascript
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

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;
}

How To Use

The "onScreen" function returns true if the element is on screen and false if not. It takes three parameters:

  • elem: The element to test for presence on the screen.
  • allowElemBehind (optional): If enabled, return true even if the element is behind of the screen area. Disabled by default.
  • allowElemAhead (optional): If enabled, return true even if the element is ahead of the screen area. Disabled by default.

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