Home  >  Article  >  Web Front-end  >  ## How to Check if an Element is Visible in the Viewport Using jQuery?

## How to Check if an Element is Visible in the Viewport Using jQuery?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-25 06:29:291001browse

## How to Check if an Element is Visible in the Viewport Using jQuery?

Detecting Visibility of Elements in the Viewport Using jQuery

Question:

How can I determine if a specific element, such as one with the class "media," is within the current browser viewport?

Answer:

To ascertain if an element is visible within the viewport, regardless of the scroll position, you can utilize a jQuery function like the following:

<code class="js">$.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;
};</code>

This function compares the element's top and bottom positions to those of the viewport. If the element's bottom position is below the viewport's top and its top position is above the viewport's bottom, it is considered visible.

To monitor changes in visibility due to scrolling or resizing, you can use the following event handler:

<code class="js">$(window).on('resize scroll', function() {
    if ($('#Something').isInViewport()) {
        // Perform actions for visible elements
    } else {
        // Perform actions for non-visible elements
    }
});</code>

Please note that this function only examines the element's vertical viewport status; it does not verify whether it extends beyond the viewport horizontally.

The above is the detailed content of ## How to Check if an Element is Visible in the Viewport Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn