4

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?

Mario
  • 6,572
  • 3
  • 42
  • 74
  • I don't really have time to answer right now, but I'll point out that it'd help if you expect some elements to be out of visibility inside a scrolling section of the page (eg a `
    ` with `overflow: auto`), or just the window.
    – eyelidlessness Nov 12 '09 at 21:29
  • You're only considering off-screen vertically. Elements can be off-screen horizontally too. – David Spector Aug 16 '23 at 16:01

2 Answers2

7
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...

Community
  • 1
  • 1
David Hedlund
  • 128,221
  • 31
  • 203
  • 222
5

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);  
}
JSuar
  • 21,056
  • 4
  • 39
  • 83
Jason
  • 51
  • 1
  • 1