From df5428c64846b4e7dd52f8d1d0a37b6da89fcda2 Mon Sep 17 00:00:00 2001 From: atomiks Date: Thu, 14 Dec 2017 21:34:48 +1100 Subject: [PATCH] Create element-is-visible-in-viewport.md https://codepen.io/anon/pen/MrwYzx Adjust the `transform: translate()` to test it out --- snippets/element-is-visible-in-viewport.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 snippets/element-is-visible-in-viewport.md diff --git a/snippets/element-is-visible-in-viewport.md b/snippets/element-is-visible-in-viewport.md new file mode 100644 index 000000000..68a690d0d --- /dev/null +++ b/snippets/element-is-visible-in-viewport.md @@ -0,0 +1,19 @@ +### Element is visible in viewport + +Use `Element.getBoundingClientRect()` and the `window.inner(Width|Height)` values +to determine if a given element is visible in the viewport. +Omit the second argument to determine if the element is entirely visible, or specify `true` to determine if +it is partially visible. + +```js +const elementIsVisibleInViewport = (el, partiallyVisible = false) => { + const { top, left, bottom, right } = el.getBoundingClientRect(); + return partiallyVisible + ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) && + ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth)) + : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth; +} +// e.g. 100x100 viewport and a 10x10px element at position {top: -1, left: 0, bottom: 9, right: 10} +// elementIsInViewport(el) -> false (not fully visible) +// elementIsInViewport(el, true) -> true (partially visible) +```