Parallax Scrolling w/jQuery

by Aaron von Schassen

HTML

<div class="container section-1">
  Welcome to this test!
</div>
<div class="container section-2">
  There is more cool stuff below...
</div>
<div class="container section-3">
  We are done with cool things!
</div>

CSS

.container {
  padding: 200px 20px 200px 20px;
  text-align: center;
  color: #FFF;
  font-weight: bold;
}

.section-1 {
  background-image: url(http://static4.wikia.nocookie.net/__cb20130612023354/harrypotter/images/d/d1/Gradient-blue-background.jpg);
  background-position: center;
}

.section-2 {
  background-image: url(http://th00.deviantart.net/fs49/PRE/f/2009/207/e/d/Orange_Desktop_Background_by_The_Dogfather.png);
  background-position: center;
}

.section-3 {
  background-image: url(http://oaklandbaptist.org/media/Green-Background.jpg);
  background-position: center;
}

JavaScript

// Y axis scroll speed
var velocity = 0.5;

function update() {
  var pos = $(window).scrollTop();
  $('.container').each(function() {
    var $element = $(this);
    // subtract some from the height b/c of the padding
    var height = $element.height() - 18;
    $(this).css('backgroundPosition', '50% ' + Math.round((height - pos) * velocity) + 'px');
  });
};

$(window).bind('scroll', update);