Skip to content

Instantly share code, notes, and snippets.

@hamstu
Last active February 7, 2024 15:20
Show Gist options
  • Star 29 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save hamstu/925c6fac166c431fe607 to your computer and use it in GitHub Desktop.
Save hamstu/925c6fac166c431fe607 to your computer and use it in GitHub Desktop.
Parallax Example: JavaScript
var ParallaxManager, ParallaxPart;
ParallaxPart = (function() {
function ParallaxPart(el) {
this.el = el;
this.speed = parseFloat(this.el.getAttribute('data-parallax-speed'));
this.maxScroll = parseInt(this.el.getAttribute('data-max-scroll'));
}
ParallaxPart.prototype.update = function(scrollY) {
if (scrollY > this.maxScroll) { return; }
var offset = -(scrollY * this.speed);
this.setYTransform(offset);
};
ParallaxPart.prototype.setYTransform = function(val) {
this.el.style.webkitTransform = "translate3d(0, " + val + "px, 0)";
this.el.style.MozTransform = "translate3d(0, " + val + "px, 0)";
this.el.style.OTransform = "translate3d(0, " + val + "px, 0)";
this.el.style.transform = "translate3d(0, " + val + "px, 0)";
this.el.style.msTransform = "translateY(" + val + "px)";
};
return ParallaxPart;
})();
ParallaxManager = (function() {
ParallaxManager.prototype.parts = [];
function ParallaxManager(elements) {
if (Array.isArray(elements) && elements.length) {
this.elements = elements;
}
if (typeof elements === 'object' && elements.item) {
this.elements = Array.prototype.slice.call(elements);
} else if (typeof elements === 'string') {
this.elements = document.querySelectorAll(elements);
if (this.elements.length === 0) {
throw new Error("Parallax: No elements found");
}
this.elements = Array.prototype.slice.call(this.elements);
} else {
throw new Error("Parallax: Element variable is not a querySelector string, Array, or NodeList");
}
for (var i in this.elements) {
this.parts.push(new ParallaxPart(this.elements[i]));
}
window.addEventListener("scroll", this.onScroll.bind(this));
}
ParallaxManager.prototype.onScroll = function() {
window.requestAnimationFrame(this.scrollHandler.bind(this));
};
ParallaxManager.prototype.scrollHandler = function() {
var scrollY = Math.max(window.pageYOffset, 0);
for (var i in this.parts) { this.parts[i].update(scrollY); }
};
return ParallaxManager;
})();
new ParallaxManager('.parallax-layer');
@bttmly
Copy link

bttmly commented Dec 23, 2014

Liked the demo! FYI on L32 the typeof operator will never return "array" (arrays are of type object). There is Array.isArray() that will give you the correct answer here though.

@hamstu
Copy link
Author

hamstu commented May 12, 2015

@nickb1080 Thanks man! Good catch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment