Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - how to determine if an Items of now viewable/in the window / below the fold

Tags:

jquery

with jquery, what's the best way to determine if an element is below the fold meaning it's also not in the window and not visible to the user?

Thanks

like image 578
AnApprentice Avatar asked Jan 11 '11 00:01

AnApprentice


People also ask

How do you know if an element is visible on screen?

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 is visible in the screen during scrolling?

To know whether the element is fully visible in viewport, you will need to check whether top >= 0, and bottom is less than the screen height. In a similar way you can also check for partial visibility, top is less than screen height and bottom >= 0.

What Javascript method tells you how far an element is from the window?

You can use . offset() to get the offset compared to the document element and then use the scrollTop property of the window element to find how far down the page the user has scrolled: var scrollTop = $(window). scrollTop(), elementOffset = $('#my-element').

How do I check if a div is visible?

Answer: Use the jQuery :visible Selector You can use the jQuery :visible selector to check whether an element is visible in the layout or not. This selector will also select the elements with visibility: hidden; or opacity: 0; , because they preserve space in the layout even they are not visible to the eye.


1 Answers

I assume you're referring to whether or not it has been scrolled out of view.

If so, try this:

if( $(window).scrollTop() + $(window).height() > $('#my_el').offset().top ) {
    // element is in view
}

Example: http://jsfiddle.net/8x4Zd/

(Click the result panel to test if the targeted element is in view. Then scroll down and repeat.)

If you want to make sure the entire element is in view, then add its .height() into the equation.

Example: http://jsfiddle.net/8x4Zd/1/

var win = $(window);
var el = $('#my_el');
var winPos = win.scrollTop() + win.height();
var elPos = el.offset().top + el.height();

if( winPos > elPos ) {
    // element is in view
}
like image 92
user113716 Avatar answered Oct 09 '22 05:10

user113716