Skip to content

Instantly share code, notes, and snippets.

@keefyhub
Created May 26, 2020 14:04
Show Gist options
  • Select an option

  • Save keefyhub/fedaaa643d89b0d47607b87ca0668b73 to your computer and use it in GitHub Desktop.

Select an option

Save keefyhub/fedaaa643d89b0d47607b87ca0668b73 to your computer and use it in GitHub Desktop.
(function ($) {
function parallaxImg(img, imgParent) {
const speed = img.data('parallax-speed')
? img.data('parallax-speed')
: 0.25;
const imgY = imgParent.offset().top;
const winY = $(this).scrollTop();
const winH = $(this).height();
const parentH = imgParent.innerHeight();
const winBottom = winY + winH;
if (winBottom > imgY && winY < imgY + parentH) {
const imgBottom = (winBottom - imgY) * speed;
const imgTop = winH + parentH;
const imgPercent = (imgBottom / imgTop) * 100 + (50 - speed * 50);
img.css({
transform: 'translate(-50%, -' + imgPercent + '%)',
});
}
}
$('[data-behaviour="parallax-image"').each(function () {
const img = $(this).find('img');
const imgParent = $(this);
$(document).on({
scroll: function () {
parallaxImg(img, imgParent);
},
ready: function () {
parallaxImg(img, imgParent);
},
});
});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment