JSFiddle - React, Tailwind, and code Playground
HTML
<div class="wrap">
<div class="background" data-speed="-10" data-type="background" data-Xposition="0%">
<div class="secondForeground" data-type="sprite" data-offsetY="150px" data-Xposition="10%" data-speed="10"></div>
<div class="firstForeground" data-type="sprite" data-offsetY="400px" data-Xposition="50%" data-speed="4"></div>
</div>
</div>
CSS
.wrap {
position:relative;
height:600px;
}
.background {
position: absolute;
top:0;
left: 0;
background: url('http://www.incredible-web.com/media/4436/background.png') no-repeat 50% 0;
width: 100%;
height: 600px;
z-index: 1;
}
.secondForeground {
position:absolute;
top:0;
left: 0;
background:url('http://www.incredible-web.com/media/4446/second_foreground.png') no-repeat 50% 150px;
width: 100%;
height: 600px;
z-index: 2;
}
.firstForeground {
position:absolute;
top:0;
left: 0;
background:url('http://www.incredible-web.com/media/4441/first_foreground.png') no-repeat 50% 400px;
width: 100%;
height: 600px;
z-index: 3;
}
JavaScript
/**
* Parallax Scrolling Tutorial
* For Smashing Magazine
* July 2011
*
* Author: Richard Shepherd
* www.richardshepherd.com
* @richardshepherd
*/
// On your marks, get set...
$(document).ready(function () {
// Cache the Window object
$window = $(window);
// Cache the Y offset and the speed of each sprite
$('[data-type]').each(function () {
$(this).data('offsetY', parseInt($(this).attr('data-offsetY')));
$(this).data('Xposition', $(this).attr('data-Xposition'));
$(this).data('speed', $(this).attr('data-speed'));
});
// For each element that has a data-type attribute
$('[data-type="background"]').each(function () {
// Store some variables based on where we are
var $self = $(this),
offsetCoords = $self.offset(),
topOffset = offsetCoords.top;
// When the window is scrolled...
$(window).scroll(function () {
// If this section is in view
if (($window.scrollTop() + $window.height()) > (topOffset) && ((topOffset + $self.height()) > $window.scrollTop())) {
// Scroll the background at var speed
// the yPos is a negative value because we're scrolling it UP!
var yPos = -($window.scrollTop() / $self.data('speed'));
// If this element has a Y offset then add it on
if ($self.data('offsetY')) {
yPos += $self.data('offsetY');
}
// Put together our final background position
var coords = '50% ' + yPos + 'px';
// Move the background
$self.css({
backgroundPosition: coords
});
// Check for other sprites in this section
$('[data-type="sprite"]', $self).each(function () {
// Cache the sprite
var $sprite = $(this);
...