Change image on Scroll

Run script when first boxes moves into the viewport

by Marius Jopen

HTML

<div id="marker">
  <div id="m-1"></div>
  <div id="m-2"></div>
  <div id="m-3"></div>
  <div id="m-4"></div>
</div>

<div id="text">CURRENT</div>
<div id="text-2">LOOPS</div>


<div id="container">
  <img id="image" src="http://mariusjopen.com/files/images/image-1.gif" />
</div>



<div id="images">
  <img class="images" id="img-1" src="http://mariusjopen.com/files/images/image-1.gif" />
  <img class="images" id="img-2" src="http://mariusjopen.com/files/images/image-2.gif" />
  <img class="images" id="img-3" src="http://mariusjopen.com/files/images/image-3.gif" />
  <img class="images" id="img-4" src="http://mariusjopen.com/files/images/image-4.gif" />
  <img class="images" id="img-5" src="http://mariusjopen.com/files/images/image-5.gif" />
  <img class="images" id="img-6" src="http://mariusjopen.com/files/images/image-6.gif" />
</div>

CSS

#container {
  height: 1500px;
}

#container img {
  position: fixed;
  height: 100%;
  width: auto;
  top: 0px;
}

#images {
  display: none;
}

#text {
  right: 0px;
  position: fixed
}

#text-2 {
  left: 0px;
  position: fixed
}

#m-1 {
  height: 100%;
  width: 100%;
  background: red;
  position: absolute;
  top: 0px;
}

#m-2 {
  height: 100%;
  width: 100%;
  background: yellow;
  position: absolute;
  top: 100%;
}

#m-3 {
  height: 100%;
  width: 100%;
  background: pink;
  position: absolute;
  top: 200%;
}

#m-4 {
  height: 100%;
  width: 100%;
  background: yellow;
  position: absolute;
  top: 300%;
}

JavaScript

$(window).scroll(function() {

  var containerHeight = $(window).height();
  var scrollPosition = $(window).scrollTop();

  $(".images").each(function(i) {
    var i = ++i;
    var count = i - 1;

    $('#text-2').text(i);

    if (scrollPosition > (containerHeight * count)) {
      var num = i;
      var img = $('#img-' + num).attr('src');
      $('#text').text(num);
      $('#image').attr("src", img);
    }

  })

})