Parallax Foreground Scrolling

This example scrolls foreground sprites using a parallax effect.

by ben74

CSS

body.parallax {
     background-color: rgb(214, 204, 173);
 }
 .final, .sprite {
     position: absolute;
 }
 .color1 {
     background-color: #42282F;
 }
 .color2 {
     background-color: #74A588;
 }
 .color3 {
     background-color: #DC9C76;
 }
 .color4 {
     background-color: #D6655A;
 }
 .size1 {
     width: 4em;
     height: 4em;
     -moz-border-radius: 2em;
     -webkit-border-radius: 2em;
     -khtml-border-radius: 2em;
     border-radius: 2em;
 }
 .size2 {
     width: 6em;
     height: 6em;
     -moz-border-radius: 3em;
     -webkit-border-radius: 3em;
     -khtml-border-radius: 3em;
     border-radius: 3em;
 }
 .size3 {
     width: 8em;
     height: 8em;
     -moz-border-radius: 4em;
     -webkit-border-radius: 4em;
     -khtml-border-radius: 4em;
     border-radius: 4em;
 }
 .size4 {
     width: 10em;
     height: 10em;
     -moz-border-radius: 5em;
     -webkit-border-radius: 5em;
     -khtml-border-radius: 5em;
     border-radius: 5em;
 }

JavaScript

$(document).ready(function () {
    var myRand = function (top) {
        /* generate whole number random from 1 to n */
        return Math.floor((Math.random() * top) + 1);
    }, wnd = $(window),
        i,
        y = 50;

    /* generate some random circles on the screen */
    for (i = 0; i < 20; i++) {
        $('body').append(
            '<div class="sprite size' + myRand(4) + ' color' + myRand(4) + '" style="top: ' + y + 'px; left: ' + (10 + myRand(wnd.width() - 180)) + 'px;" data-speed="' + myRand(4) + '" data-y="' + y + '"></div>');
        y += myRand(150);
    }
    /* 
     * generate a final div at the bottom so the body height
     * does not change as sprites are moved
     */
    $('body').append('<div class="final" style="top: ' + y + 'px;">&nbsp;</div>');

    /* scroll event */
    wnd.scroll(function () {
        /* loop through all the circle sprites */
        $('.sprite').each(function () {
            /* Move the sprite based on speed and scroll calculation */
            var sprite = $(this),
                yPos = -(wnd.scrollTop() / sprite.data('speed'));
            yPos = Math.floor(yPos) + sprite.data('y');
            sprite.css('top', yPos + 'px');

        }); // sprites

    });
});