Skip to content

Instantly share code, notes, and snippets.

@davidbwaters
Last active December 22, 2020 03:38
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 davidbwaters/1a59d12f643ef8fb3c30d1d99e0b68a5 to your computer and use it in GitHub Desktop.
Save davidbwaters/1a59d12f643ef8fb3c30d1d99e0b68a5 to your computer and use it in GitHub Desktop.
intersection observer direction helpers
let previousY = 0
let previousRatio = 0
function getObserverEntryInfo(entry, previousY, previousRatio) {
let direction
let approach
const hasLargerRatio =
entry.intersectionRatio > previousRatio
if (entry.boundingClientRect.y < previousY) {
direction = 'down'
}
else {
direction = 'up'
}
if (direction === 'down') {
if (hasLargerRatio && entry.isIntersecting) {
approach = 'entering'
}
else {
approach = 'leaving'
}
}
if (direction === 'up' && entry.isIntersecting) {
if (hasLargerRatio) {
approach = 'entering'
}
else {
approach = 'leaving'
}
}
return {
direction: direction,
approach: approach
}
}
function ioCallback(entries) {
entries.forEach(entry => {
const info = getObserverEntryInfo(entry)
const direction = info.direction
const approach = info.approach
if (direction === 'down' && approach === 'entering') {
}
previousY = currentY
previousRatio = currentRatio
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment