check if element is within viewport

How to Check if Element is Visible in Viewport

Viewport is the user’s visible area of web page. It varies from device to device. Often you may need to check if an HTML element of your web page is visible in your browser’s viewport. In this article, we will learn how to check if element is visible in Viewport of your browser, using JavaScript.


How to Check if Element is Visible in Viewport

Here is a simple JavaScript function to check if element is visible in viewport.

function isElementInViewport (el) {

    // Special bonus for those using jQuery
    if (typeof jQuery === "function" && el instanceof jQuery) {
        el = el[0];
    }

    var rect = el.getBoundingClientRect();

    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /* or $(window).height() */
        rect.right <= (window.innerWidth || document.documentElement.clientWidth) /* or $(window).width() */
    );
}

In the above code, we use getBoundingClientRect() function which returns the DOMRect object which contains the size and position of your element. We check the top and left values to check if they are greater than 0, that is, whether they are within the viewport. We also compare the bottom and right values of the rectangle, with those of your browser window, using window.innerHeight and window.innerWidth, to determine if the element is inside the viewport. This function returns a Boolean value of True or False, which you can use for further processing.

Also read:

How to Check if Element is Hidden in JavaScript
How to Stay On Same Tab After Page Refresh
How to Select Element By Text in JavaScript
How to Select Element By Name in JavaScript
How to Get Value of Selected Radio

Leave a Reply

Your email address will not be published. Required fields are marked *