Skip to content

Instantly share code, notes, and snippets.

@webag
Last active January 14, 2020 20:56
Show Gist options
  • Save webag/238c8fd214cde715b8accdb66abad83f to your computer and use it in GitHub Desktop.
Save webag/238c8fd214cde715b8accdb66abad83f to your computer and use it in GitHub Desktop.
js parallax inertia
<div class="js-parallax" data-parallax="-0.05"></div>
<div class="js-parallax" data-parallax="0.1"></div>
/***********************
parallax BEGIN
***********************/
function getCoords(elem) {
const box = elem.getBoundingClientRect();
return {
top: box.top + pageYOffset,
left: box.left + pageXOffset
};
}
function scrollParallax(current) {
let currentMultiplier = 0.1;
let defaultOffset = 0;
let windowHalf = window.innerHeight / 2;
let elementHeight = current.offsetHeight;
current.dataset.pos = '0';
if (current.dataset.parallax) {
currentMultiplier = parseFloat(current.dataset.parallax);
}
const make = function () {
let normallevel = window.pageYOffset + windowHalf - elementHeight / 2;
let currentDelta = current.dataset.pos;
let newDelta;
let tweenDelta;
let posResult;
defaultOffset = parseFloat(getCoords(current).top * currentMultiplier);
newDelta = parseInt((normallevel * currentMultiplier));
tweenDelta = (currentDelta - ((currentDelta - newDelta) * 0.05)).toFixed(1);
posResult = tweenDelta - defaultOffset;
current.style.transform = 'translate3d(0px, ' + posResult + 'px, 0px)';
current.dataset.pos = tweenDelta;
window.requestAnimationFrame(make);
};
if (window.requestAnimationFrame) {
make();
}
}
document.addEventListener('DOMContentLoaded', function () {
if (device.desktop()) {
const parallaxElements = document.querySelectorAll('.js-parallax');
for (let i = 0; i < parallaxElements.length; i++) {
scrollParallax(parallaxElements[i]);
}
}
});
/***********************
parallax END
***********************/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment