Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing element visibility in jQuery

What is the best way to determine if an element is truly visible on the page? As in pixels are being changed both because the element is not hidden via CSS and is in the visible part of a scrollable area (the window or some overflowing block element)?

I imagine I'll need to first check .is(':hidden') against the element and its parents. I would then need to iterate through all parents and the window, checking for overflow scroll/auto/hidden, then compare that parent element's scroll position and size against the original element's position and size. And I would also need to check for absolute positioning and look at z-indexes, as well.

Is there an easier way?

like image 851
MikeWyatt Avatar asked Jun 01 '10 21:06

MikeWyatt


People also ask

How can we check element visibility?

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.

Is visible in jQuery?

The :visible selector in jQuery is used to select every element which is currently visible. It works upon the visible elements. The elements that are consuming space in the document are considered visible elements. The height and width of visible elements are larger than 0.

How do you check if an element is visible after scrolling?

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.


1 Answers

There's a plugin for that. jQuery inview event plugin

like image 80
mVChr Avatar answered Nov 15 '22 08:11

mVChr