Change images on scroll

by lovromar

HTML

<img src="http://placekitten.com/100/100" />

CSS

img {
    position: fixed;
    top: 0;
    left: 0;
}
body {
    height: 10000px;
}

JavaScript

// Array of images to swap between
var images = ['http://placekitten.com/100/100', 'http://placekitten.com/100/200', 'http://placekitten.com/100/300'];

var totalImages = images.length;

var documentHeight = $(document).height();

// Work out how often we should change image (i.e. how far we scroll between changes)
var scrollInterval = Math.floor(documentHeight / totalImages);

$(document).scroll(function () {
    // Which one should we show at this scroll point?
    i = Math.floor($(this).scrollTop() / scrollInterval);
    // Show the corresponding image from the array
    $('img').attr('src', images[i]);
});