Skip to content

Instantly share code, notes, and snippets.

@timc1
Last active February 13, 2019 06:04
Show Gist options
  • Save timc1/241f6253312db1912f8535f3382e064e to your computer and use it in GitHub Desktop.
Save timc1/241f6253312db1912f8535f3382e064e to your computer and use it in GitHub Desktop.
Using IntersectionObserver to track current and previously focused DOM elements. Demo: https://codesandbox.io/s/o599joo75z
// polyfill
import 'intersection-observer'
const setupIntersectionObserver = elements => {
// keep track of the current focused section as well as the previous.
// when the user scrolls up/reverse, we trigger the previous
let current, previous
const observer = new IntersectionObserver(
entries => {
entries.forEach(entry => {
const id = entry.target.getAttribute('id')
if (entry.isIntersecting) {
if (current !== id) {
previous = current
current = id
// a function to toggle a css class for the focused link
updateCurrentActiveLink(current)
}
} else if (current === id && previous) {
current = previous
updateCurrentActiveLink(current)
}
}
})
},
{
// trigger when 25% of the element is in the viewport
threshold: [0.25],
}
)
elements.forEach(el => observer.observe(el))
return observer
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment