Last active
February 15, 2019 01:37
-
-
Save timc1/0093b689480421893e6aef6d6fd0e1d8 to your computer and use it in GitHub Desktop.
Parallax scrolling using requestAnimationFrame & transforms
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
function Parallax({ className }) { | |
let elements = [] | |
let screenHeight, animationId | |
window.requestAnimationFrame = | |
window.requestAnimationFrame || | |
window.mozRequestAnimationFrame || | |
window.webkitRequestAnimationFrame || | |
window.msRequestAnimationFrame || | |
function(f) { | |
return setTimeout(f, 1000 / 60) | |
} | |
const setup = () => { | |
// Cleanup before setting up new requestAnimationFrame. | |
cancelAnimationFrame(animationId) | |
const parallaxElements = Array.from( | |
document.querySelectorAll(`.${className}`) | |
) | |
if (!parallaxElements.length) { | |
console.error( | |
'No parallax elements found. Add a class name of "parallax" to any element you would like to target.' | |
) | |
return | |
} | |
elements = parallaxElements.map(el => { | |
const { top, height } = el.getBoundingClientRect() | |
const speed = Number(el.getAttribute('data-parallax')) | |
return { | |
el, | |
originalTop: top + window.scrollY, | |
height, | |
speed, | |
} | |
}) | |
screenHeight = window.innerHeight | |
animate() | |
} | |
const animate = () => { | |
elements.forEach(({ el, originalTop, height, speed }) => { | |
const { top: newTop } = el.getBoundingClientRect() | |
let translate | |
if (screenHeight >= originalTop) { | |
translate = (window.scrollY / speed) * -1 | |
} else { | |
translate = (newTop - height / 2) / speed | |
} | |
el.style.transform = `translate3d(0, ${Math.floor(translate)}px, 0)` | |
}) | |
animationId = requestAnimationFrame(animate) | |
} | |
const cancelAnimationFrame = | |
window.cancelAnimationFrame || | |
window.mozCancelAnimationFrame || | |
clearTimeout | |
const cleanup = () => { | |
cancelAnimationFrame(animationId) | |
window.removeEventListener('resize', setup) | |
} | |
const init = () => { | |
setup() | |
window.addEventListener('resize', setup) | |
} | |
return { | |
init, | |
cleanup, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment