Skip to content

Instantly share code, notes, and snippets.

@jdvivar
Last active March 8, 2020 11:47
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 jdvivar/08381a3a2fcd1592ad1d58d7afae4bfb to your computer and use it in GitHub Desktop.
Save jdvivar/08381a3a2fcd1592ad1d58d7afae4bfb to your computer and use it in GitHub Desktop.
Improved pixel anchor observer from
// Res.: https://css-tricks.com/styling-based-on-scroll-position/
let anchor = document.getElementById('pixel-anchor')
if (!anchor) {
const interval = window.setInterval(() => {
anchor = document.getElementById('pixel-anchor')
if (anchor) {
window.clearInterval(interval)
createObserver(anchor)
}
}, 100)
}
const createObserver = anchor => {
if ('IntersectionObserver' in window && anchor) {
const observerCallback = entries => {
if (entries[0].boundingClientRect.y < 0) {
document.body.classList.add('header-not-at-top')
} else {
document.body.classList.remove('header-not-at-top')
}
}
new window.IntersectionObserver(observerCallback).observe(anchor)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment