How to check if an element is in the view of the user with jquery

Sebastien picture Sebastien · Nov 22, 2011 · Viewed 30.4k times · Source

I have a very big draggable div in my window. This div has a smaller window.

<div id="draggable-area" style="width:500px;height:500px;overflow:hidden">
 <div id="draggable" style="width:5000px;height:5000px">
     <ul>
         <li></li>
         <li></li>
         <li></li>
         <li></li>
         <li></li>
         ....
     </ul>
  </div>
</div>  

How can I know if the li element is visible in the user viewport (I mean really visible, not in the overflow area)?

Answer

Alex Peattie picture Alex Peattie · Nov 22, 2011

To check if an element is in the current veiwport:

function elementInViewport(el) {
  var top = el.offsetTop;
  var left = el.offsetLeft;
  var width = el.offsetWidth;
  var height = el.offsetHeight;

  while(el.offsetParent) {
    el = el.offsetParent;
    top += el.offsetTop;
    left += el.offsetLeft;
  }

  return (
    top >= window.pageYOffset &&
    left >= window.pageXOffset &&
    (top + height) <= (window.pageYOffset + window.innerHeight) &&
    (left + width) <= (window.pageXOffset + window.innerWidth)
  );
}

(Source)

For a more robust method, I'd recommend Viewport Selectors, which allow you to just do:

$("#elem:in-viewport")