Xel Xel - 1 month ago 11
CSS Question

How to trigger an image to move when users scroll the page?

Is there any way to make an image move up when users scroll the page? I have 2 square images (each 400px in wide and height), both are visible. The left image is fixed by position. The right image is positioned 200px below the left image. I need to make the right image to move up by 200px (get aligned with the left image) when we scroll the page. Then the it stays still on that position.

I found the one on this page is quite the same with what I'm trying to create http://jessandruss.us/#waiting The difference is my images are all visible, while on this page the overflow of the left image is hidden and it gets back to its original position when users scroll up.

Really appreciate any help on this matter. Thank you.

Answer
$(document).ready(function(){
  var aligned = false; // A flag to tell us when the images are aligned
    $(window).scroll(function(){ 
    if($(this).scrollTop() == 192 ) { // when the window scroll to the alignment point... 
        aligned = true; // the images are aligned
    }
    if (aligned) { // if they're aligned... 
        $(".image-2").css("top", 8 + $(this).scrollTop()) // match .image-2's top css property
    }                                                   // to the window's scrollTop value, +
                                                        // 8px for the body's margin.  
  })
})

Here's a JSFiddle with what I think you want.

There's simply a boolean to tell us when the images are lined up. When they are, image-2's CSS property 'top' is matched to the window's scrollTop value.

The boolean variable is currently hard coded to tell us when the images are lined up (I looked at the window's scrollTop value when they were lined up, 192 in this case). This isn't a great approach since it won't account for changes in the images' positions or sizes, but this should be enough to get to going.

Comments