Skip to content

Instantly share code, notes, and snippets.

@darkcris1
Created February 7, 2021 10:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darkcris1/42e8e0e9d2092de4c2daaf13f5e1f0d0 to your computer and use it in GitHub Desktop.
Save darkcris1/42e8e0e9d2092de4c2daaf13f5e1f0d0 to your computer and use it in GitHub Desktop.
Add a callback if the element is on the viewport
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