Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)?

like image 254
Sebastien Avatar asked Nov 22 '11 15:11

Sebastien


People also ask

How do you check if an element is in the viewport jQuery?

Check if element is visible in viewport using jquery:If the bottom position of the viewport is greater than the element's top position AND the top position of the viewport is less than the element's bottom position, the element is in the viewport (at least partially).

How do you check if an element is in the viewport?

To find out if the whole element is inside of the viewport we can simply check if the top and left value is bigger or equal to 0, that the right value is less or equal to the viewport height ie window. innerWidth and that the bottom value is less or equal to window. innerHeight.

Is visible in jQuery?

version added: 1.0jQuery( ":visible" )Elements are considered visible if they consume space in the document. Visible elements have a width or height that is greater than zero. Elements with visibility: hidden or opacity: 0 are considered visible, since they still consume space in the layout.

Is Div visible jQuery?

You can use .is(':visible') selects all elements that are visible.


1 Answers

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")
like image 197
Alex Peattie Avatar answered Oct 22 '22 01:10

Alex Peattie