noob2014 noob2014 - 1 year ago 73
CSS Question

How do you make a picture change as you scroll down a web page?

I found this really cool effect on this page, scroll 2/3 down to see it It's a "pencil" image(multiple images from different angles) that change as you scroll down, it will do that same if you scroll up. link is here

Anyway, can anyone tell me how i could implement that in my site? Or the name of the effect so i can look it up.

Much appreciated.

Answer Source

Three steps:

  1. Listen to the scroll event.
  2. Get the current scroll position.
  3. Set the image source based on that position.

var imageEl = document.getElementById('fake-image');

function getSrc(scrollPos) {
  if (scrollPos < 200) return 'image one.jpg';
  if (scrollPos < 300) return 'image two.jpg';
  if (scrollPos < 400) return 'image three.jpg';
  if (scrollPos < 500) return 'image four.jpg';
  if (scrollPos < 600) return 'image five.jpg';
  return 'image six.jpg';

window.addEventListener('scroll', function() {
  imageEl.textContent = getSrc(window.scrollY);
#fake-image {
  background: aliceblue;
  height: 5000px;
  padding-top: 50%;
  font-size: 30px;
<div id="fake-image">
  Fake image

You'll probably want to pre-load the images or, as another answer said, use show/hide and have multiple images.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download