alan
alan

Reputation: 79

Change statically positioned image with scroll

I'm trying to change the source of a statically positioned image based upon the scroll position of a window.

Basically, I want to cycle through MRI scan images depending on where the viewport is relative to the page. I want to get through all 100+ images over the length of the page. This length will change, so I'm trying to work out how to make it proportional.

I confess that I am new to coding so it may be best to use pseudocode rather than trying to code:

window.image1position == ( 1 / [#images] ) * document.totalheight
window.image2position == ( 2 / [#images] ) * document.totalheight
...

 if window.scrollposition == window.image1position

     set image.src = image1.png

 elseif window.scrollposition == window.image2position

     set image.src = image2.png
...

Would anyone be able to help me with this idea? Any input would be very much appreciated.

Alan

Upvotes: 0

Views: 118

Answers (1)

Serlite
Serlite

Reputation: 12258

Since you didn't specify whether jQuery was acceptable, I threw together something quick to do this using plain JavaScript. Rather than determining the appropriate scroll distances for each image beforehand, I elected to do this on the fly referencing array indices. (This assumes you have an <img id="changeImg"> element):

// Store image sources in array to keep track of them
var imgArray = ["img1.jpg",
               "img2.jpg",
               "img3.jpg"];

// Get scrollable height of body, calculate stepsize to go between images
// Partially taken from http://stackoverflow.com/questions/1145850/how-to-get-height-of-entire-document-with-javascript
var body = document.body, html = document.documentElement;
var totalHeight = Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight ) - window.innerHeight;
var stepSize = totalHeight/imgArray.length;

// Bind to scroll event
window.onscroll = function(){
    var scrolled = document.body.scrollTop;
    var img = document.getElementById("changeImg");

    // Determine correct index to use, and swap src
    var imgIndex = Math.min(Math.floor(scrolled/stepSize), imgArray.length - 1); 
    img.src = imgArray[imgIndex];
};

Here's a JSFiddle demonstration to show you the code in action. Hope this helps! Let me know if you have any questions.

Upvotes: 2

Related Questions