user1949366
user1949366

Reputation: 465

Image change on scroll

Following on from another SO Question

This script changes an image on page scroll. However this script would be excessively large if it was for example, used for frames of a video with 200+ images. Is it possible to shorten this script for use with large number of files?

Many thanks

Upvotes: 1

Views: 4732

Answers (1)

gvee
gvee

Reputation: 17171

Minor code tweaks...

JSFiddle

http://jsfiddle.net/gvee/ygkWH/6/

HTML

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

[illustrative] CSS

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

JQuery

// Array of images to swap between
var images = [];

// Add 200 items to array
for (i = 0; i < 200; i++) {
    images.push('http://placekitten.com/' + (100 + i) + '/' + (100 + i));
}

var totalImages = images.length;

var pageHeight = $(document).height() - $(window).height();

// Work out how often we should change image (i.e. how far we scroll between changes)
var scrollInterval = Math.floor(pageHeight / 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]);
    $('b').text('Frame: ' + i);
});

Upvotes: 8

Related Questions