Skip to content

Instantly share code, notes, and snippets.

@azproduction
Created November 13, 2012 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save azproduction/4066951 to your computer and use it in GitHub Desktop.
Save azproduction/4066951 to your computer and use it in GitHub Desktop.
getBordersInViewport

Function returns sides of element that are fully in viewport

   +-----+ <- element .b-logo__image
   |     |
+--+-----+---+ <- viewport
|  |     |   |
|  +-----+   |
|            |
+------------+
var element = document.querySelector('.b-logo__image');
getBordersInViewport(element);
/*{
    "top":false,
    "right":false,
    "bottom":true,
    "left":false,
    "all":false
}*/
function getBordersInViewport(element) {
var boundingClientRect = element.getBoundingClientRect(),
viewportWidth = innerWidth,
viewportHeight = innerHeight;
var bordersViewport = {
top: boundingClientRect.top >= 0 && boundingClientRect.top <= innerHeight,
right: boundingClientRect.right >= 0 && boundingClientRect.right <= viewportWidth,
bottom: boundingClientRect.bottom >= 0 && boundingClientRect.bottom <= innerHeight,
left: boundingClientRect.left >= 0 && boundingClientRect.left <= viewportWidth,
all: false
};
if (!bordersViewport.top || !bordersViewport.bottom) {
bordersViewport.left = bordersViewport.right = false;
} else if (!bordersViewport.left || !bordersViewport.right) {
bordersViewport.top = bordersViewport.bottom = false;
}
bordersViewport.all = bordersViewport.top &&
bordersViewport.right &&
bordersViewport.bottom &&
bordersViewport.left;
return bordersViewport;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment