'How can I change an image when the user scrolls down?

I can easily animate on scroll down png and jpg format images easily, but when I scroll down gif images, It repeatedly animated when I scroll down more.Here i provide gif image

this is the script i use

<script type="text/javascript">
        $(function () { 
            $(window).scroll(function () {
                if ($(this).scrollTop() > 10) { 
                    $('.navbar-brand-img img').attr('src','asserts/images/innvert.gif');
                }
                if ($(this).scrollTop() < 49) { 
                    $('.navbar-brand-img img').attr('src','asserts/images/expand.gif');
                }
            })
        });
</script>

Anyone can help

I want to animate logo of gif images i provide the model website that animation used

Thrashio



Solution 1:[1]

Setting the src= of an image will always restart the image if it's animated, even if it's the same src=. Your issue is that you re-set the src= (to the same value) on every scroll so it's constantly restarting.

You can store whether or not you've already set the image - a simple flag (or .data on the img) would suffice.

$(function() {
  $(window).scroll(function() {

    // set to true/false here based on your initial image
    var invert = false;

    if ($(this).scrollTop() > 10) {
      if (!invert) {
          $('.navbar-brand-img img').attr('src', 'asserts/images/innvert.gif');
          invert = true;
      }
    }
    if ($(this).scrollTop() < 49) {
      if (invert) {
          $('.navbar-brand-img img').attr('src', 'asserts/images/expand.gif');
          invert = false;
      }
    }
  })
});

Note your >10 doesn't match with <49 so may cause problems.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1