Parallax Effect

There is a better version of this on the new site at: http://riceball.com/yet-another-…

This is a short snippet of code to do the popular “parallax” effect for headings. This code has two boxes. The second box helps you see how to deal with a box that’s not at the top of the page.

There’s not much to it. You make some boxes and set the background-position based on the window.scrollY value.


<html>
    <head>
        <style type="text/css">
            #box1 {
                height: 350px;
                background-image: url(trafficjam.jpg);
            }
            #box2 {
                height: 350px;
                background-image: url(gavilan2.jpg);
            }
        </style>
    </head>
    <body>
        <div id='box1'>
            <h1>Parallax Demo</h1>
        </div>
        <div id='box2'>
            <h1>PARALLAX DEMO</h1>
        </div>
        <script>
            window.setInterval(function () {
                var box2ofst = -100;
                document.getElementById('box1').style.backgroundPosition = 
                    '0px ' + window.scrollY/10 + 'px';
                document.getElementById('box2').style.backgroundPosition = 
                    '0px ' + (box2ofst + window.scrollY/10) + 'px';
            }, 50);
        </script>
    </body>
</html>