Check if element is in the wieport


/ Published in: JavaScript
Save to your folder(s)

Copied from somewhere, probably stackoverflow.


Copy this code and paste it in your HTML
  1. var checkViewport = function(el){
  2.  
  3. var minTop = jQuery(document).scrollTop(),
  4. minLeft = jQuery(document).scrollLeft(),
  5.  
  6. maxTop = minTop + jQuery(window).height(),
  7. maxLeft = minLeft + jQuery(window).width(),
  8.  
  9. $myElement = el,
  10.  
  11. elementOffset = $myElement.offset(),
  12. elementHeight = $myElement.height(),
  13. elementWidth = $myElement.width();
  14.  
  15. if (
  16. (elementOffset.top > minTop && elementOffset.top + elementHeight < maxTop) &&
  17. (elementOffset.left > minLeft && elementOffset.left + elementWidth < maxLeft)
  18. ) {
  19. console.log('entire element is visible');
  20. } else {
  21. console.log('entire element is not visible');
  22. }
  23. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.