Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if element is visible after scrolling?

I'm loading elements via AJAX. Some of them are only visible if you scroll down the page. Is there any way I can know if an element is now in the visible part of the page?

like image 964
yoavf Avatar asked Jan 28 '09 10:01

yoavf


People also ask

How do you know if an element is visible in scroll?

Summary. Use the getBoundingClientRect() method to get the size of the element and its relative position to the viewport. Compare the position of the element with the viewport height and width to check if the element is visible in the viewport or not.

How do you know if an element gets visible in the screen during scrolling react?

There are two ways to know when an element gets visible / hidden in the screen during scrolling : Listening to the window scroll event. Observing the element for visibility using Intersection Observer API.

How do you know if an element is visible?

We can do the following to check an element's visibility in the viewport: Get the bounding rect of the DOM element using the getBoundingClientRect . This method returns an object with an element's width, height, and position relative to the viewport.

How do I check if a div is visible?

You can use .is(':visible') selects all elements that are visible.


1 Answers

This should do the trick:

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

Simple Utility Function This will allow you to call a utility function that accepts the element you're looking for and if you want the element to be fully in view or partially.

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'); } 
like image 124
Scott Dowding Avatar answered Oct 03 '22 11:10

Scott Dowding