Skip to content

Instantly share code, notes, and snippets.

@patmigliaccio
Last active October 31, 2019 13:43
Show Gist options
  • Save patmigliaccio/c19a662d7e89bc166b304ee3c1764963 to your computer and use it in GitHub Desktop.
Save patmigliaccio/c19a662d7e89bc166b304ee3c1764963 to your computer and use it in GitHub Desktop.
Adds a simple CSS transformation moving effect on window scroll to elements with the `.scrollax` class.
(function() {
/**
* Adds moving effect on scroll to elements with the `.scrollax` class.
*
* Optional `.sx-negative` class to move in opposite direction.
*
* @param {number} [antiMagnitude=40] Amount to reduce the magnitude of the effect by
* @version 1.2.0
* @author Pat Migliaccio <pat@patmigliaccio.com>
* @license MIT
*/
function scrollax(antiMagnitude) {
var scrollaxEles = document.getElementsByClassName("scrollax");
Array.from(scrollaxEles).forEach(function(ele, i) {
window.addEventListener("scroll", function() {
setTimeout(function() {
parallax(ele);
}, 0);
});
});
function parallax(ele) {
var eleOffset = offset(ele),
windowHeight =
"innerHeight" in window
? window.innerHeight
: document.documentElement.offsetHeight;
var pageOffsetTop = window.scrollY - eleOffset.document.top;
if (eleOffset.window.top < windowHeight && pageOffsetTop < 0) {
var eleTransformOffset = pageOffsetTop / (antiMagnitude || 40);
if (ele.classList.contains("sx-negative")) {
eleTransformOffset *= -1;
}
ele.style.transform = "translate(0%, " + eleTransformOffset + "%)";
}
}
// Reference: https://plainjs.com/javascript/styles/get-the-position-of-an-element-relative-to-the-document-24/
function offset(el) {
var rect = el.getBoundingClientRect(),
scrollLeft = window.pageXOffset || document.documentElement.scrollLeft,
scrollTop = window.pageYOffset || document.documentElement.scrollTop;
return {
document: { top: rect.top + scrollTop, left: rect.left + scrollLeft },
window: { top: rect.top, left: rect.left }
};
}
}
scrollax(30);
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment