Created
February 7, 2021 10:56
-
-
Save darkcris1/42e8e0e9d2092de4c2daaf13f5e1f0d0 to your computer and use it in GitHub Desktop.
Add a callback if the element is on the viewport
This file contains hidden or 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
function onViewport(elem, callback, options = {}) { | |
if (elem instanceof Element) elem = [elem] | |
// Initial option | |
// Unobserve the element if it is on the viewport for optimizing purposes | |
const { abortEarly = true } = options | |
let counter = 0 | |
const observer = new IntersectionObserver((entries, self) => { | |
entries.forEach((el) => { | |
if (el.isIntersecting) { | |
callback(el.target, counter) | |
counter++ | |
abortEarly && self.unobserve(el.target) | |
} | |
}) | |
}, options) | |
elem.forEach((el) => { | |
observer.observe(el) | |
}) | |
return { | |
destroy: () => { | |
observer.disconnect() | |
}, | |
} | |
} | |
// Usage | |
const buttons = document.querySelectorAll("button"); | |
onViewport(buttons,(element,i)=>{ | |
element.style.transform = `translateY(${i}*100px)` | |
}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment