l00per l00per - 1 year ago 164
Javascript Question

Change Image on Scroll Position

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 Source

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.

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