Star Scroller

Simple parallax example

by Alma Grace

HTML

<div style="height:20000px"></div>

CSS

body {
    background-color:#000;
    background-image:url(http://bglabs.evade.netdna-cdn.com/files/gears-background-1587.png), url(http://bglabs.evade.netdna-cdn.com/files/gears-background-1587.png), url(http://bglabs.evade.netdna-cdn.com/files/gears-background-1587.png);
    background-position:100px 0, 0 100px, 250px 200px;
}

JavaScript

//paralax scrolling

// First, let's bind the 'scroll' event so that it runs our parallax
window.addEventListener("scroll", function () {
    // We'll be using this scrollTop value a lot, so let's bind it
    var st = document.body.scrollTop;
    // Then, simply update the style so that the backgroundPosition is calculated based on it
    document.body.style.backgroundPosition = 
        // Let's make this bottom background fancy, and wave it back and forth as a sine wave
        100 + Math.sin(st/5) * 10 + "px 0," +
        // We'll make these next two scroll at slightly different speeds
        "0 " + Math.floor(100+st*1.5) + "px," +
        "250px " + Math.floor(200+st*2) + "px";
    /* There are much better, more flexible ways you can use this. Don't just update the background positions, but have multiple elements on your page that can move about. You could even change the scrolling pattern if you used something like this:
    if(st > document.querySelector(".some_cool_looking_element").offsetTop + 100) {
      // Start doing something once your element is 100px on the screen
    }
    */
});