Skip to content

Instantly share code, notes, and snippets.

@bastienrobert
Created October 10, 2017 12:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bastienrobert/c9fc5ef43c40b2a648c72389c51fac69 to your computer and use it in GitHub Desktop.
Save bastienrobert/c9fc5ef43c40b2a648c72389c51fac69 to your computer and use it in GitHub Desktop.
Parallax library
/*
* 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