Skip to content

Instantly share code, notes, and snippets.

@marcandrewb
Created July 1, 2020 03:09
Show Gist options
  • Save marcandrewb/e28794f8ec62b49831a6a2a66649d9f8 to your computer and use it in GitHub Desktop.
Save marcandrewb/e28794f8ec62b49831a6a2a66649d9f8 to your computer and use it in GitHub Desktop.
export function isElementInView(container: HTMLElement, element: HTMLElement, partial: boolean) {
if (!container || !element) {
return false;
}
const containerBounds = container.getBoundingClientRect();
const elementBounds = element.getBoundingClientRect();
const containerBoundsLeft = Math.floor(containerBounds.left);
const containerBoundsRight = Math.floor(containerBounds.right);
const elementBoundsLeft = Math.floor(elementBounds.left);
const elementBoundsRight = Math.floor(elementBounds.right);
// Check if in view
const isTotallyInView = elementBoundsLeft >= containerBoundsLeft && elementBoundsRight <= containerBoundsRight;
const isPartiallyInView =
partial &&
((elementBoundsLeft < containerBoundsLeft && elementBoundsRight > containerBoundsLeft) ||
(elementBoundsRight > containerBoundsRight && elementBoundsLeft < containerBoundsRight));
// Return outcome
return isTotallyInView || isPartiallyInView;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment