Created
March 19, 2013 13:42
-
-
Save georgestephanis/5196196 to your computer and use it in GitHub Desktop.
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…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ↓ 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