Home >Web Front-end >JS Tutorial >How Can I Check if Dynamically Loaded Elements Are Visible After Scrolling?

How Can I Check if Dynamically Loaded Elements Are Visible After Scrolling?

Linda Hamilton
Linda HamiltonOriginal
2024-12-20 09:36:091002browse

How Can I Check if Dynamically Loaded Elements Are Visible After Scrolling?

Resolving Visibility of Dynamically Loaded Elements after Scrolling

Problem Statement:

When dynamically loading elements through AJAX, it can be challenging to determine if they appear within the visible area of the page, especially if the page requires scrolling.

Solution:

To determine an element's visibility after scrolling, we can leverage a JavaScript function called isScrolledIntoView():

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));
}

Alternative Approach:

An alternative utility function, Utils.isElementInView(), provides both a fullyInView and partiallyInView option:

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();

Usage:

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

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

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