Created
August 18, 2021 08:12
-
-
Save EmielZuurbier/6321dd39cfe277498e94a36510ba515e to your computer and use it in GitHub Desktop.
Detect elements in viewports. Uses the Intersection Observer API to async detect elements.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Returns an array of elements that are currently in view. | |
* @param {string} selector A CSS selector to query elements. | |
* @param {boolean} partially Detect elements that are partially in view. Otherwise they would have to be fully in view. | |
* @returns {Promise<HTMLElement[]>} | |
*/ | |
const getElementsInView = (selector = '*', partially = true) => | |
new Promise(resolve => { | |
const elements = document.querySelectorAll(selector) | |
if (elements.length === 0) { | |
resolve([]) | |
} | |
const elementsInView = [] | |
const onIntersect = (entries, observer) => { | |
for (const { target, isIntersecting } of entries) { | |
if (isIntersecting) { | |
elementsInView.push(target) | |
} | |
} | |
observer.disconnect() | |
resolve(elementsInView) | |
} | |
const observerInit = { | |
root: null, | |
rootMargin: '0px', | |
threshold: partially ? [0] : [1] | |
} | |
const observer = new IntersectionObserver(onIntersect, observerInit) | |
for (const element of elements) { | |
observer.observe(element) | |
} | |
}) | |
export default getElementsInView |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment