Home > Web Front-end > JS Tutorial > How Can I Detect if a Dynamically Loaded Element is Visible After Scrolling?

How Can I Detect if a Dynamically Loaded Element is Visible After Scrolling?

Susan Sarandon
Release: 2024-12-20 02:08:10
Original
131 people have browsed it

How Can I Detect if a Dynamically Loaded Element is Visible After Scrolling?

Detecting Element Visibility after Scrolling

For elements dynamically loaded using AJAX, determining their visibility within the viewport can be crucial. This is particularly relevant for elements that appear after scrolling. Here's an effective method to address this issue:

Using a Custom Function:

The following function checks whether an element is visible within the current viewport:

function isScrolledIntoView(elem) {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
Copy after login

Utilizing a Utility Function:

A more versatile option is to employ a utility function that offers customization:

function Utils() {

}

Utils.prototype = {
    constructor: Utils,
    isElementInView: function (element, fullyInView) {
        var pageTop = $(window).scrollTop();
        var pageBottom = pageTop + $(window).height();
        var elementTop = $(element).offset().top;
        var elementBottom = elementTop + $(element).height();

        if (fullyInView === true) {
            return ((pageTop < elementTop) && (pageBottom > elementBottom));
        } else {
            return ((elementTop <= pageBottom) && (elementBottom >= pageTop));
        }
    }
};

var Utils = new Utils();
Copy after login

Usage:

To determine if an element is visible, simply call this function:

var isElementInView = Utils.isElementInView($('#flyout-left-container'), false);

if (isElementInView) {
    console.log('in view');
} else {
    console.log('out of view');
}
Copy after login

By implementing these methods, you can easily detect the visibility of dynamically loaded elements, enabling optimized page interactions and user experiences.

The above is the detailed content of How Can I Detect if a Dynamically Loaded Element is Visible After Scrolling?. 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