Last active
October 21, 2017 21:59
-
-
Save carlhannes/799b76d083576188a79b9101773961e3 to your computer and use it in GitHub Desktop.
Very simple ES6 JavaScript background-position parallax function using requestAnimationFrame
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
export default function attachParallax(elm) { | |
document.addEventListener('mousemove', (e) => { | |
window.requestAnimationFrame(() => { | |
const left = (e.clientX / window.innerWidth) * 5; | |
const top = (e.clientY / (window.innerHeight)) * 5; | |
elm.style.backgroundPosition = `${47.5 + left}% ${47.5 + top}%`; | |
}); | |
}, false); | |
} | |
/* | |
Usage: | |
attachParallax(document.querySelector('div.mydiv')); | |
Also needs the following CSS-variables: | |
background-size: 110% auto; | |
background-image: url('myfile.png'); | |
background-position: 50% 50%; | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment