Home > Web Front-end > JS Tutorial > How Can I Determine if an Element is Visible After Scrolling?

How Can I Determine if an Element is Visible After Scrolling?

Susan Sarandon
Release: 2024-12-19 03:19:09
Original
987 people have browsed it

How Can I Determine if an Element is Visible After Scrolling?

Ensuring Element Visibility After Scrolling

Identifying Scroll-Hidden Elements

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.

Solution

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));
}
Copy after login

Extended Utility Function

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));
    }
  }
};
Copy after login

Enhanced Usage

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');
}
Copy after login

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!

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