Home >Web Front-end >JS Tutorial >How Can I Determine if an Element is Visible After Scrolling?
When loading content dynamically via AJAX, some elements may remain concealed unless scrolling is performed. Determining their visibility within the currently visible portion of the page becomes crucial.
To check if an element is fully or partially visible after scrolling, utilize the following function:
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)); }
Introduce a utility function that supports both full and partial visibility checks:
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)); } } };
Enhance the code with this utility function:
var Utils = new Utils(); var isElementInView = Utils.isElementInView($('#flyout-left-container'), false); if (isElementInView) { console.log('in view'); } else { console.log('out of view'); }
By implementing these functions, you can effectively detect element visibility after scrolling and respond accordingly.
The above is the detailed content of How Can I Determine if an Element is Visible After Scrolling?. For more information, please follow other related articles on the PHP Chinese website!