Skip to content

Instantly share code, notes, and snippets.

@AndreKelling
Created November 8, 2018 13:52
Show Gist options
  • Save AndreKelling/0c173267f41bd3f076ecb903e75226b6 to your computer and use it in GitHub Desktop.
Save AndreKelling/0c173267f41bd3f076ecb903e75226b6 to your computer and use it in GitHub Desktop.
for vertical centred background-image on #masthead
var timeout;
window.addEventListener('scroll', function () {
// If there's a timer, cancel it
if (timeout) {
window.cancelAnimationFrame(timeout);
}
timeout = window.requestAnimationFrame(function () {
const scrollPosition = window.pageYOffset;
const bgParallax = document.getElementById('masthead');
const limit = bgParallax.offsetTop + bgParallax.offsetHeight;
if (scrollPosition > bgParallax.offsetTop && scrollPosition <= limit) {
bgParallax.style.backgroundPositionY = (50 - (150 * scrollPosition/limit)) + '%';
} else {
bgParallax.style.backgroundPositionY = '50%';
}
});
}, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment