Switch Image on Page Scroll

by Dedi Wibisono

HTML

<div id="frame"></div>
<br /><br /><br /><br />
<div class="control1">Scroll the page and see how the background image is switched. »» </div>
<br /><br /><br /><br /><br />
<br /><br /><br /><br />
<div class="control2">This div also scrolls with the page.</div>
<br /><br />
<button>This is a normal button</button>
<br /><br />
<div class="control2">This is another div that scrolls with the page.</div>

CSS

html, body {
    min-height: 1200px; /* for testing the scroll bar */
}
div#frame {
    display: block;
    position: fixed;
    width: 300px;
    height: 300px;
    z-index: -1;
}
div.control1 {
    position: absolute;
    background: #FFCC00;
    border: 1px solid black;
    padding: 10px;
    width: 200px;
    text-align: right;
    right: 10px;
}
div.control2 {
    background: #EEEEEE;
    border: 1px solid black;
    padding: 10px;
}

JavaScript

$(document).ready(function () {
    switchImage();
});

$(window).scroll(function () {
    switchImage();
});

var images = ["http://dummyimage.com/300x300/000000/fff",
              "http://dummyimage.com/300x300/ffcc00/000",
              "http://dummyimage.com/300x300/ff0000/000",
              "http://dummyimage.com/300x300/ff00cc/000",
              "http://dummyimage.com/300x300/ccff00/000"];

function switchImage() {
    var sTop = $(window).scrollTop();
    var index = sTop > 0 ? $(document).height() / sTop : 0;
    index = Math.round(index) % images.length;
    console.log(index);
    $("#frame").css('background-image', 'url(' + images[index] + ')');
}