Skip to content

Instantly share code, notes, and snippets.

@thiamsantos
Created July 19, 2017 21:27
Show Gist options
  • Save thiamsantos/ece681c598227e2ec058f68377666c60 to your computer and use it in GitHub Desktop.
Save thiamsantos/ece681c598227e2ec058f68377666c60 to your computer and use it in GitHub Desktop.
Check if a element will appear in the screen
const throttle = (limit, fn) => {
let wait = false
return (...args) => {
if (!wait) {
fn(...args)
wait = true
setTimeout(() => {
wait = false
}, limit)
}
}
}
const willAppear = element => {
const rect = element.getBoundingClientRect()
const safetyMargin = window.innerHeight / 2
return rect.bottom >= -safetyMargin && rect.top <= window.innerHeight + safetyMargin
}
const el = document.getElementById('second')
window.addEventListener('scroll', throttle(100, () => {
console.log('willAppear', willAppear(el))
}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment