Skip to content

Instantly share code, notes, and snippets.

@daniloparrajr
Last active September 27, 2017 01:37
Show Gist options
  • Save daniloparrajr/615a41c9e1982dca1f642fa71b0559bb to your computer and use it in GitHub Desktop.
Save daniloparrajr/615a41c9e1982dca1f642fa71b0559bb to your computer and use it in GitHub Desktop.
/*--------------------------
* Simple Parallax script
*
* Usage: just add data-parallax="scroll" to the the element you want to have parallax effect
* make sure that the element has background-image and height dimension set.
* Example: <div data-parallax="scroll" style="background-image: url("path/to/img"); height: 300px;"></div>
--------------------------*/
var parallaxSection = document.querySelectorAll('[data-parallax="scroll"]');
//Set default style for the parallax element
parallaxSection.forEach(function(el,index,array) {
el.style.backgroundSize = "cover";
el.style.backgroundRepeat = "no-repeat";
el.style.backgroundPosition = "bottom center";
});
//Listen to scroll event and update background position on scroll
window.addEventListener("scroll", function() {
var scrolledHeight= window.pageYOffset;
parallaxSection.forEach(function(el,index,array) {
var limit= el.offsetTop+ el.offsetHeight;
el.style.backgroundPosition = "bottom -" + (scrolledHeight - el.offsetTop) /2+ "px center";
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment