How to check if an element is visible in the current viewport as we scroll?

When we are writing code in JavaScript we usually do the DOM manipulation very often. In many cases, we need to fire an event when an element shows up on the current viewport. As we already know the current viewport is the currently visible area of the web page.

The size of the viewport may vary with the device. The small mobile phone screen has a smaller viewport compare to the laptop screen viewport.

Now we may want this in many ways. We may want to fire the event when the entire element is visible on the viewport as we scroll. We may also want if the element overlaps with the viewport the event should fire. Following are the codes for both the cases:

When element entirely visible on 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() */
    );
}

When element overlaps on viewport:

function isElementInViewport(el) {
    var rect = el.getBoundingClientRect();

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

Reference:
How can I tell if a DOM element is visible in the current viewport?

Github:
https://github.com/imakewebthings/waypoints
https://github.com/morr/jquery.appear
https://github.com/ryanve/verge/

Share