Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine if an HTML element is offscreen?

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?

like image 238
Mario Avatar asked Dec 18 '22 04:12

Mario


2 Answers

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

like image 71
David Hedlund Avatar answered Dec 19 '22 17:12

David Hedlund


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);  
}
like image 39
Jason Avatar answered Dec 19 '22 19:12

Jason