Search code examples
jqueryfor-loopscrollsrc

Incrementing image src based on scroll position with jQuery


I would like to use jQuery to have the background-image attribute of a div increase by 1 every time the user scrolls a certain amount, like 30 pixels. I have about 40 images named frame1.jpg, frame2.jpg, etc. I successful achieved this effect by setting a condition for each step (show frame1 after 30 pixels, frame 2 after 60 pixels, etc.), but when I try to do it with a "for" loop, as soon as I scroll, it goes to frame3.jpg, the image before the last, and after the next 30 pixels it jumps to the last image (frame4.jpg).

I will actually use this in a horizontal parallax-style layout but I wanted to understand the technique in the simplest possible way first.

Here is what I tried (with only 4 frames), and any help would be appreciated. Thanks!

HTML:

<div id="container">
   <div id="inner"></div>
</div>

CSS:

#container {
  width: 100%;
  height: 2000px;
  position:absolute;
}

#inner { 
  position:fixed;
  top:0;
  width:100%;
  height:400px;
  background-size:cover;
}

Javascript:

$("#inner").css("background-image", "url(http://holis.ro/frames/frame1.jpg");

$(window).scroll(function() {
   var value = $(this).scrollTop();
    for (var i = 0; i < 4; i++) {
      if (value < 40 * i)
      $("#inner").css("background-image", "url(http://holis.ro/frames/frame" + i +".jpg)");
      else if (value < 40 * (i+1))
      $("#inner").css("background-image", "url(http://holis.ro/frames/frame" + (i+1) +".jpg)"); 
    }
});

Solution

  • Find a rolation between scrollTop() value.

    And user this :

    var oldindex = 1;    
    $(window).scroll(function() {
    
        //floor or ceil to get int valeu
        var newindex = Math.Math.ceil($(this).scrollTop()/ 30 ) //30 px
    
        if(newindex!=oldindex && newindex<=40){ //add limitation 40 images
            $("#inner").css("background-image", "url(http://holis.ro/frames/frame"+newindex+".jpg");
            oldindex = newindex
        }
    });