How to usethe Scroll event method in HTML

In this approach, we are using a scroll event listener without using the getBoubdingClinetRect() method, As the user scrolls, you can continuously determine if a DOM element is visible by comparing its position to the viewport’s dimensions and taking appropriate action according to the element’s visibility state.

Syntax:

object.addEventListener("scroll", myScript);

Example: In this example, we are using the above-explained approach.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>Scroll Event Example</title>
    <style>
        body {
            height: 1000px;
        }
  
        .myDiv {
            width: 200px;
            height: 200px;
            background-color: red;
            margin: 400px auto;
        }
    </style>
</head>
  
<body>
    <div id="div1" class="myDiv"></div>
  
    <script>
        function isElementVisible(element) {
            const elementTop = element.offsetTop;
            const elementBottom = elementTop 
                + element.offsetHeight;
            const viewportTop = window.pageYOffset;
            const viewportBottom = viewportTop 
                + window.innerHeight;
  
            return (
                elementBottom > viewportTop &&
                elementTop < viewportBottom
            );
        }
  
        const elementToCheck = document.getElementById('div1');
  
        window.addEventListener('scroll', () => {
            if (isElementVisible(elementToCheck)) {
                console.log('Element is visible in viewport');
            } else {
                console.log('Element is not visible in viewport');
            }
        });
    </script>
</body>
  
</html>


Output:



How to Check a DOM Element is Visible in Current Viewport ?

In this article, we will see how to find DOM element is visible in the current viewport or not. To determine if a DOM element is visible in the current viewport, we can compare its position and dimensions using the getBoundingClientRect() function with the dimensions of the viewport and also we can use the scroll event method.

We have a few methods that can be utilized to find whether a DOM element is visible in the current viewport, which is discussed below:

  • Using the getBoundingClientRect() Method
  • Using the Scroll Event Method

Similar Reads

Approach 1: Using the getBoundingClientRect() Method

The JavaScript function getBoundingClientRect() returns a DOMRect object that represents the size and position of an element in relation to the viewport. In order to measure and position elements precisely, it offers characteristics like x, y, width, and height....

Syntax:

value.getBoundingClientRect();...

Approach 2: Using the Scroll event method

...