Skip to content

Instantly share code, notes, and snippets.

@yurydelendik
Last active December 20, 2015 21:09
Show Gist options
  • Select an option

  • Save yurydelendik/6195643 to your computer and use it in GitHub Desktop.

Select an option

Save yurydelendik/6195643 to your computer and use it in GitHub Desktop.
Checking if DOM element is in view
function isInView(element) {
// set initial bounds
var bounds = element.getBoundingClientRect();
var left = bounds.left, top = bounds.top;
var right = bounds.right, bottom = bounds.bottom;
var currentElement = element;
while (true) {
if (!currentElement.offsetParent) {
return false; // 'display: none;' not visible
}
// checking if any parent clips it
for (var p = currentElement.parentElement; p; p = p.parentElement) {
var parentBounds = p.getBoundingClientRect();
// intersect
left = Math.max(left, parentBounds.left);
top = Math.max(top, parentBounds.top);
right = Math.min(right, parentBounds.right);
bottom = Math.min(bottom, parentBounds.bottom);
if (left >= right || top >= bottom) {
return false;
}
}
// checking also parent window of the frame
var defaultView = currentElement.ownerDocument.defaultView;
var frameElement = defaultView.frameElement;
if (!frameElement) {
break; // no iframe parent, stopping
}
// fixing and cliping rect for the current window/view
left -= defaultView.pageXOffset; right -= defaultView.pageXOffset;
top -= defaultView.pageYOffset; bottom -= defaultView.pageYOffset;
left = Math.max(0, left);
top = Math.max(0, top);
right = Math.min(defaultView.innerWidth, right);
bottom = Math.min(defaultView.innerHeight, bottom);
if (left >= right || top >= bottom) {
return false;
}
// shifting to the frame coordinates and continue using iframe parents
bounds = frameElement.getBoundingClientRect();
left += bounds.left; right += bounds.left;
top += bounds.top; bottom += bounds.top;
currentElement = frameElement;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment