Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A quick and dirty Parallax implementation I worked up for a project. DISCLAIMER! Will not work in older versions of IE! Which ... y'know ... GOOD. It applies to all elements with a data-parallax attribute on them. When the element's parent item hits the top of the screen, it switches from horizontal motion to vertical motion. By default, it will…
window.onscroll = function() {
// Mobile doesn't normally work well with Parallax, so let's bail out.
if( navigator.userAgent.match(/mobile/i) != null ) return;
els = d.querySelectorAll( '[data-parallax]' );
for( i in els ) {
el = els[i];
if( typeof el.parentNode == 'undefined' ) continue;
multiplier = el.getAttribute( 'data-parallax' );
offset = ( el.parentNode.offsetTop - window.pageYOffset ) / multiplier;
xOffset = 0 - Math.max( offset, 0 );
if( el.hasAttribute( 'data-parallax-flip-horz' ) )
xOffset = 0 - xOffset;
yOffset = Math.min( offset, 0 );
if( el.hasAttribute( 'data-parallax-flip-vert' ) )
yOffset = 0 - yOffset;
transform = 'translateY(' + yOffset + 'px) translateX(' + xOffset + 'px)';
el.style.webkitTransform = transform;
el.style.MozTransform = transform;
el.style.msTransform = transform;
el.style.OTransform = transform;
el.style.transform = transform;
}
}
/* Usage:
<div style="padding-top:20em;">
<h1 data-parallax="2">I enter from the left, then go up</h1>
<h2 data-parallax="3" data-parallax-flip-horz="true">I enter from the right, then go up</h2>
<h3 data-parallax="4" data-parallax-flip-vert="true" >I enter from the left, then &darr; I go!</h3>
<img src="http://placekitten.com/300/300/" alt="I enter from the right, then down I go!" data-parallax="2" data-parallax-flip-vert="true" data-parallax-flip-horz="true" />
</div>
/**/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment