Skip to content

Instantly share code, notes, and snippets.

@lucas-pelton
Created October 29, 2015 17:24
Show Gist options
  • Save lucas-pelton/fe2fcb91fe1753bfb81c to your computer and use it in GitHub Desktop.
Save lucas-pelton/fe2fcb91fe1753bfb81c to your computer and use it in GitHub Desktop.
Simple, smooth parallax with css transforms
var parallaxDivs = document.getElementsByClassName("parallaxBG");
var updateSize = function() {
updateScroll();
}
var updateScroll = function() {
for(var i = 0; i < parallaxDivs.length; i++) {
var parallaxDiv = parallaxDivs[i];
var offsetTop = $(parallaxDiv).offset().top;
var startVisible = offsetTop - window.innerHeight;
var endVisible = offsetTop + parallaxDiv.offsetHeight;
var visibleSection = (window.pageYOffset - startVisible) / (endVisible - startVisible);
//debugger;
if(visibleSection >= 0 && visibleSection <= 1.0) {
var divHeight = parallaxDiv.offsetHeight;
var transformAmount = divHeight * 0.6 * (visibleSection - 0.5);
//parallaxDiv.style.backgroundPositionY = transformAmount + "px"
parallaxDiv.style.transform = 'translate3d(0px, ' + + transformAmount + 'px, 0px)';
//console.log('visible: ' + visibleSection)
}
}
}
function setupParallax() {
$(window).on('scroll', function() {
window.requestAnimationFrame(updateScroll);
});
$(window).on('resize', function() {
window.requestAnimationFrame(updateSize);
});
/*
window.addEventListener('scroll', updateScroll, false);
window.addEventListener('resize', updateSize, false);
*/
updateSize();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment