Andrew C Andrew C - 2 months ago 19
jQuery Question

Change Image to gif on scroll with jquery

I am trying to change a couple of images to gifs as you scroll down the page. Currently I have the images changing to gifs on scroll, but the gif resets as soon as you scroll again. I would like the gif to continue to play even if you are scrolling.

Here is my jquery:

$(window).scroll(function(){
var top = $(window).scrollTop();

var img1Top = $('.wrap').offset().top;
if(img1Top){
$('.wrap').attr('src','../wrap.gif');
};


var img2Top = $('.vest').offset().top;
if(top=(img2Top)){
$('.vest').attr('src','../vest.gif');
};

var img3Top = $('.loop').offset().top;
if(top=(img3Top)){
$('.loop').attr('src','../loop.gif');
};

});

Answer

1. Your code is currently resetting the src every time the page scrolls, and although the path may not be changing, it will cause the image to refresh.

You need to wrap each src change in a conditional that only updates the image if it hasn't already been updated.

2. Your if statements are using = instead of ==, which won't work.

3. Doing == to compare the top of the window to the top of the elements is not the best way to do this, only because if you scroll fast enough, the chances of this event being called when the two values are identical are very slim. You should use >= instead.

$(window).scroll(function(){
  var top = $(window).scrollTop();

  var img1Top = $('.wrap').offset().top;
  if(img1Top && $('.wrap').attr('src') != '../wrap.gif'){
    $('.wrap').attr('src','../wrap.gif');
  };


  var img2Top = $('.vest').offset().top;
  if(top >= img2Top && $('.vest').attr('src') != '../vest.gif'){
    $('.vest').attr('src','../vest.gif');
  };

  var img3Top = $('.loop').offset().top;
  if(top >= img3Top && $('.loop').attr('src') != '../loop.gif'){
    $('.loop').attr('src','../loop.gif');
  };

});
Comments