<div class="container">
<!-- putting the 'elements' we want to paralax into
larger containers to ease positioning -->
<div class="level three">
<div class="element"></div>
</div>
<div class="level two">
<div class="element"></div>
</div>
<!-- putting level one here to make sure it's on 'top',
also keeps me from having to mess with z-index. -->
<div class="level one">
<div class="element"></div>
</div>
</div>
CSS
.container{
/* add height to page */
height: 1500px;
}
/* style all the level elements globally */
.level{
width: 100%;
/* Note the position: fixed here. This will cause the element
to stay put when the window is scrolled. That way we can
do what we want from javascript. */
position: fixed;
/* always list both positioning properties, ie compat. */
top: 0;
left: 0;
}
/* style all 'elements' globally */
.element{
position: absolute;
top: 20px;
left: 0;
width: 100%;
height: 100px;
}
/* style the level one element */
.level.one .element{
background: blue;
opacity: 0.75;
}
/* style the level two element */
.level.two .element{
background: green;
opacity: 0.75;
}
/* style the level three element */
.level.three .element{
background: red;
opacity: 0.75;
}
JavaScript
// Use jQuery to get reference to levels
$l1 = $('.level.one');
$l2 = $('.level.two');
$l3 = $('.level.three');
// Need reference to window so we can get how far we scrolled
$window = $(window);
// Listen to the scroll event from window so we know when the window
// is scrolled by the user
$window.on('scroll', function(e){
var distance, l1Top, l2Top, l3Top;
// the distance scrolled can be grabbed from window.scrollY
distance = window.scrollY;
// now just take the distance and do something with it
// each level responds to the distance by multiplying it
// by some arbitrary factor.
l1Top = distance * 0.2 + 'px';
l2Top = distance * 0.15 + 'px';
l3Top = distance * 0.1 + 'px';
// last step is to adjust the css, jQuery makes that pretty
// straight forward.
$l1.css('top', l1Top);
$l2.css('top', l2Top);
$l3.css('top', l3Top);
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.