How can I determine using jQuery that a given element is above the top of the viewable window area or below the bottom of it? This would allow me to determine whether the item was offscreen and in which direction.
Ideally:
var topPos = $(this).relativeToTop();
var bottomPos = $(this).relativeToBottom();
var isOnScreen = topPos >= 0 && bottomPos >= 0;
Is there a plugin or example online somewhere?
var off = $(this).offset();
var t = off.top;
var l = off.left;
var h = $(this).height();
var w = $(this).width();
var docH = $(window).height();
var docW = $(window).width();
var isEntirelyVisible = (t > 0 && l > 0 && t + h < docH && l+ w < docW);
EDIT somewhere in there, it might be an idea to check $(document).scrollTop() as well, depending on how you want the script to deal with scroll state...
Thanks David for the post, it helped me solve my 'fully visible element' issue, however I had to tailor the recommendation to the following, because my parent div
area was larger than the visible window size. The following code works for me, although I only have to worry about the vertical.
elem
is a jquery object, and this will probably only work for html5
function isFullyVisible (elem) {
var off = elem.offset();
var et = off.top;
var el = off.left;
var eh = elem.height();
var ew = elem.width();
var wh = window.innerHeight;
var ww = window.innerWidth;
var wx = window.pageXOffset;
var wy = window.pageYOffset;
return (et >= wy && el >= wx && et + eh <= wh + wy && el + ew <= ww + wx);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With