Created
October 10, 2017 12:23
-
-
Save bastienrobert/c9fc5ef43c40b2a648c72389c51fac69 to your computer and use it in GitHub Desktop.
Parallax library
This file contains hidden or 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
/* | |
* Add a dataset to your target like this : | |
* data-parallax='1' | |
* | |
* Parallax strenght can be define with the number | |
* | |
*/ | |
var els = [] | |
function scrollHandler(event) { | |
for (var i = 0; i < els.length; i++) { | |
var el = els[i] | |
var factor = parseInt(el.getAttribute("data-parallax")) | |
var bodyRect = document.body.getBoundingClientRect(), | |
elRect = el.getBoundingClientRect() | |
var percent = Math.round((elRect.top + el.offsetHeight) / (window.innerHeight + el.offsetHeight) * 100) | |
percent = Math.max(0, Math.min(100, percent)) | |
var translation = Math.round(factor * (percent - 50)) | |
el.style.transform = "translateY(" + translation + "px)" | |
} | |
} | |
function initParallax() { | |
els = document.querySelectorAll("[data-parallax]") | |
scrollHandler() | |
document.addEventListener("scroll", scrollHandler) | |
window.addEventListener("resize", scrollHandler) | |
} | |
initParallax() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment