Last active
March 8, 2020 11:47
-
-
Save jdvivar/08381a3a2fcd1592ad1d58d7afae4bfb to your computer and use it in GitHub Desktop.
Improved pixel anchor observer from
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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