Skip to content

Instantly share code, notes, and snippets.

@kotarok
Last active December 1, 2015 10:12
Show Gist options
  • Save kotarok/f669cce0fce93d8d36d9 to your computer and use it in GitHub Desktop.
Save kotarok/f669cce0fce93d8d36d9 to your computer and use it in GitHub Desktop.
Simple and easy parallax effect.
/**
* Parallax class provides parallax effect for multiple elements.
* @constructor
*/
var Parallax = function(expr) {
this.targets = [];
if (typeof expr === 'string') {
this.init(expr);
}
};
/**
* Initialise.
* @method init
* @param {string} expr CSS selector string to apply parallax effect.
*/
Parallax.prototype.init = function(expr) {
this.targets = document.querySelectorAll(expr);
this.repositionAll();
window.addEventListener('scroll', this.repositionAll.bind(this));
};
/**
* Apply reposition method to all target elements.
* Called by window.onscroll event.
* @method repositionAll
*/
Parallax.prototype.repositionAll = function() {
this.scrollY = window.scrollY;
this.winHeight = document.documentElement.clientHeight;
Array.prototype.forEach.call(this.targets, this.reposition.bind(this));
};
/**
* Main method to reposition backgound image respective to scroll amount.
* @method reposition
*/
Parallax.prototype.reposition = function(obj) {
var bgpy = ((obj.offsetTop - this.scrollY) /
(this.winHeight - obj.clientHeight));
obj.style.backgroundPosition = 'center ' + (bgpy * 100 + '%');
};
// Super shortened version. Not 100% compatible with original script.
function c(a){this.b=document.querySelectorAll(a);this.a();window.addEventListener("scroll",this.a.bind(this))}c.prototype.a=function(){var a=window.scrollY,d=document.documentElement.clientHeight;Array.prototype.forEach.call(this.b,function(b){b.style.backgroundPosition="center "+((b.offsetTop-a)/(d-b.clientHeight)*100+"%")})};window.Parallax=c;
<!doctype>
<html>
<head>
<title>Parallax Sample</title>
<style>
.parallax {
height: 400px; /* whatever */
background-repeat: repeat-x;
background-size: auto 130%; /* bigger than 100% for height*/
}
</style>
</head>
<div class="parallax" style="background-image: url(//placekitten.com/900/500)">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
</div>
<div class="parallax" style="background-image: url(//placekitten.com/900/501)">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
</div>
<script src="Parallax.js"></script>
<script>
new Parallax('.parallax');
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment