Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benjaminsinger/8e46fa8851a681617d0769bab7611926 to your computer and use it in GitHub Desktop.
Save benjaminsinger/8e46fa8851a681617d0769bab7611926 to your computer and use it in GitHub Desktop.
Parallax Background Images Using 3d Transforms
/*
trans3dparallax.js
Author: Ben Singer
Desc: A (very) simple jQuery-powered parallax effect for maximum smoothness with minimal effort.
*/
var parallaxPushr = function() {
var parallaxPushr = {};
var parallaxBlocks = [];
parallaxPushr.panelParallax = function() {
var parallaxItem = jQuery('[data-parallax]');
parallaxItem.wrap('<div class="parallax-overflow-hider" style="overflow:hidden;height:100%;min-height:100%;">');
parallaxItem.each(function(index) {
var parallaxBlock = {};
parallaxBlock.element = jQuery(this);
parallaxBlock.height = parallaxBlock.element.height();
parallaxBlock.width = parallaxBlock.element.width();
parallaxBlocks.push(parallaxBlock);
});
}(); // push desired parallax panels into parallaxBlocks array.
parallaxPushr.scrollHandler = function() {
jQuery.each(parallaxBlocks, function(index, parallaxBlock) {
// Code to see which parallax block is currently visible within the viewport...
// Code to update `transform: translate3d` value... if IE8/IE9 support is required, users can fallback to background image / translateY, respectively.
var siteH = jQuery(window).height();
var windowTop = jQuery(window).scrollTop();
var blockTop = parallaxBlock.element.offset().top;
var difference = windowTop - blockTop;
//only parallax blocks that are in view!
if ((windowTop > (blockTop - siteH)) && (windowTop < (blockTop + siteH))) {
parallaxBlock.element.css({
'-webkit-transform': 'translate3d(0,' + Math.round(difference / 3) + 'px, 0)',
'transform': 'translate3d(0,' + Math.round(difference / 3) + 'px, 0)'
});
}
if ( windowTop <= 0 ) {
parallaxBlock.element.css({
'-webkit-transform': 'translate3d(0,0,0)',
'transform': 'translate3d(0,0,0)'
});
}
});
}; // scrollHandler function end
// prevent jittery scroll on retina devices by using RAF.
jQuery(window).on('scroll load resize', function(){
window.requestAnimationFrame(parallaxPushr.scrollHandler);
});
return parallaxPushr;
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment