Skip to content

Instantly share code, notes, and snippets.

@carlhannes
Last active October 21, 2017 21:59
Show Gist options
  • Save carlhannes/799b76d083576188a79b9101773961e3 to your computer and use it in GitHub Desktop.
Save carlhannes/799b76d083576188a79b9101773961e3 to your computer and use it in GitHub Desktop.
Very simple ES6 JavaScript background-position parallax function using requestAnimationFrame
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