Home >Web Front-end >JS Tutorial >How Can I Check if Dynamically Loaded Elements Are Visible 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!