Change Image on Scroll Position

l00per picture l00per · Jun 16, 2014 · Viewed 34.8k times · Source

I would like to change an image on a certain scroll position. For example:

Scroll 100px show img1.jpg

Scroll 200px show img2.jpg

Scroll 300px show img3.jpg

Here I found an example what I mean.

Any ideas?

Answer

Lior picture Lior · Jun 16, 2014

You can use the onScroll event to listen for scrolling, check at what position the scrollbar is and make the image change or whatever your heart desires. You can read more about onScroll event here. A basic code will be something like this:

var onScrollHandler = function() {
  var newImageUrl = yourImageElement.src;
  var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  if (scrollTop > 100) {
     newImageUrl = "img1.jpg"
  }
  if (scrollTop > 200) {
     newImageUrl = "img2.jpg"
  }
  if (scrollTop > 300) {
     newImageUrl = "img3.jpg"
  }
  yourImageElement.src = newImageUrl;
};
object.addEventListener ("scroll", onScrollHandler);

Of course yourImageElement should be replaced with the image element you want to change.

If you have jQuery availble you can use the .scroll() method instead of the event listener and the .scrollTop() to get the scrollbar position.

Also, you might want to look at some scroll/paralex libraries like skrollr.