Check Element Visibility After Scrolling with jQuery or JS

Introduction

In the world of web development, it's often necessary to determine whether an HTML element is visible after scrolling. This can be crucial for a variety of reasons, such as triggering animations, loading content dynamically, or tracking user behavior.

In this Byte, we'll explore how to check the visibility of an element after scrolling in both plain JavaScript and jQuery.

Element Visibility in the DOM

Before diving into the code, it's important to understand what we mean by an element's visibility in the DOM. When we talk about an element being visible, we mean that it is within the viewport, i.e., the portion of the webpage currently visible in the browser window. An element can exist in the DOM but still be invisible if it's outside the viewport, either above or below the area currently being viewed.

Note: An element can also be invisible if it's hidden using CSS properties like display: none or visibility: hidden. However, for the purpose of this article, we're only concerned with visibility in terms of the viewport.

Why Check Element Visibility After Scrolling?

You might wonder why it's necessary to check an element's visibility after scrolling. There are several reasons for this. Imagine you might want to load content dynamically as the user scrolls, a common technique in infinite scroll implementations. Or you maybe you want to trigger an animation or event when a certain element comes into view. You'll notice that checking element visibility can also be useful for tracking user behavior and interaction with your site.

Checking Element Visibility in Plain JavaScript

Now let's get down to the code. Here's how you can check an element's visibility using plain JavaScript:

function isElementVisible(el) {
    const rect = el.getBoundingClientRect();
    const vWidth = window.innerWidth || doc.documentElement.clientWidth;
    const vHeight = window.innerHeight || doc.documentElement.clientHeight;

    // Check if the element is out of bounds
    if (rect.right < 0 || rect.bottom < 0 || rect.left > vWidth || rect.top > vHeight) return false;

    // Return true if any of the above disjunctions are false
    return true;
}

// Usage
const myElement = document.querySelector('#myElement');
console.log(isElementVisible(myElement));  // Outputs: true or false

In this code, we first get the bounding rectangle of the element using the getBoundingClientRect() method. This gives us an object with the properties top, right, bottom, and left, which represent the coordinates of the element's edges relative to the viewport.

We then compare these coordinates with the viewport's dimensions, which we get using window.innerWidth, window.innerHeight, or their fallbacks. If the element's coordinates are outside the viewport's dimensions, we know the element is not visible and return false. Otherwise, we return true.

This function can be used with any element in the DOM, and it will tell you whether that element is currently visible in the viewport.

Checking Element Visibility with jQuery

jQuery, as you probably know, is a fast, small, and very popular JavaScript library. It makes things like HTML document traversal and manipulation, event handling, and animation much easier with an easy-to-use API that works across most browsers.

To check if an element is visible after scrolling, jQuery provides a method called :visible selector. However, this method alone cannot detect if the element is actually in the viewport after scrolling.

To do what we want, we can create a custom function.

$.fn.isInViewport = function() {
    var elementTop = $(this).offset().top;
    var elementBottom = elementTop + $(this).outerHeight();
    var viewportTop = $(window).scrollTop();
    var viewportBottom = viewportTop + $(window).height();
    return elementBottom > viewportTop && elementTop < viewportBottom;
};
Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

To use this function, simply call it on any jQuery object like this:

$(window).on('resize scroll', function() {
    if ($('#myElement').isInViewport()) {
        console.log('#myElement is visible');
    } else {
        console.log('#myElement is not visible');
    }
});

Scroll Event Listener in JavaScript

JavaScript provides the scroll event for detecting when an element's scroll position has changed. The scroll event is fired when the document view or an element has been scrolled.

Here is how we can set up a scroll event listener on the window object:

window.addEventListener('scroll', function() {
    console.log('Scrolled!');
});

Note: The scroll event is fired for any scrollable element and the window object. However, it is not fired for elements that do not have a scrollbar.

This is helpful since we can then check if our target element is in the viewport, but only after a scroll event.

Scroll Event Listener in jQuery

In jQuery, we can set up a scroll event listener using the .scroll() method. It attaches an event handler function to the scroll event, or triggers that event on an element.

Here is how we can set up a scroll event listener on the window object using jQuery:

$(window).scroll(function() {
    console.log('Scrolled!');
});

This will log 'Scrolled!' to the console each time the window is scrolled.

Again, this event callback is helpful to us in figuring out if an element is in view since it allows us to only check when the user scrolls, as opposed to setting some kind of timer to periodically check.

Conclusion

In this Byte, we learned how to check if an element is visible after scrolling using both plain JavaScript and jQuery. We also explored how to set up scroll event listeners in both JavaScript and jQuery. While jQuery provides a more concise and easy-to-use syntax, it's always good to understand how to achieve the same result in pure JavaScript.

Last Updated: August 28th, 2023
Was this helpful?

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms