Home > Web Front-end > JS Tutorial > body text

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

Patricia Arquette
Release: 2024-10-25 06:29:29
Original
1000 people have browsed it

## 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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!