Replace Image with another on scroll

by Omar Atta

HTML

<!-- Replace Image with another on scroll, using jQuery -- By Omar A. -->
<!-- To use it in your site 
  ===> Src: primary image
  ===> data-animate: secondary image
-->
<div id="wrapper">
  <div class="long-space"></div>
  
  <img class="target-img" src="https://2.bp.blogspot.com/-tN06GKuwzkM/WDzYkJMwR1I/AAAAAAAAIn8/HFHbWRl9__kpWbAFpzER29y23XHy-fdSACLcB/s800-c-k-rw/y0rs8Fo.gif
  " data-animate="https://2.bp.blogspot.com/-tN06GKuwzkM/WDzYkJMwR1I/AAAAAAAAIn8/HFHbWRl9__kpWbAFpzER29y23XHy-fdSACLcB/s800/y0rs8Fo.gif
">
  
  <div class="long-space"></div>
</div>

CSS

/* For Demo Only */
.long-space {
  display: block;
  height: 1250px;
}
img {
  width: 400px;
  height: 300px;
}
img.animated {
  border: 2px solid red;
}

JavaScript

var selector	= $(".target-img"),
		fixed			= selector.attr( "src" ),
    animate		= selector.data("animate"),
    target		= selector.offset().top - 100,
    target_end= selector.offset().top + 300;

$(window).scroll(function() {
	if ($(this).scrollTop() > target && $(this).scrollTop() < target_end) {
  	selector.attr("src", animate).addClass("animated");
  }else {
  	selector.attr("src", fixed).removeClass("animated");
  }
});