1

I have a white menu icon in PNG format that I want to change to green menu icon in PNG format and I tried to use the fading effect. It works at first and changes on scroll but when I keep scrolling it keeps flickering the green icon, however it stops when I stop scrolling as well. I'm not sure why this is happening or how can I fix it, couldn't really find the related questions. I'd appreciate your help. Thanks in advance here is my code:

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

          if (scroll >= 50) {
            $(".show_nav img").fadeOut(function() {
              $(this).attr("src","../img/icons/menu-green.png").fadeIn();
            });

          } else {
            $(".show_nav img").fadeOut(function() {
              $(this).attr("src","../img/icons/menu-white.png").fadeIn();
            });
          }
      });
Danny
  • 33
  • 6
  • 1
    Your event handler is on the `scroll` event. Why is it surprising that it fires on scroll? – isherwood Mar 31 '22 at 14:24
  • You probably want to do a visibility check before fading in repeatedly. – isherwood Mar 31 '22 at 14:25
  • Well I've used the same scroll event on other elements to transform translate up and down and it works without problems so I thought this would be useful for it as well. – Danny Mar 31 '22 at 14:25
  • Different cause, but can use the same answer as asked earlier: https://stackoverflow.com/a/71693314/2181514 – freedomn-m Mar 31 '22 at 14:30
  • *every* time you scroll, you fadeOut set the src and fadeIn - add a `console.log` inside your scroll event - there's *a lot* of them. You can add a flag so it only happens once. There are methods to check if currently fading, eg [`:animated`](https://stackoverflow.com/questions/6992626/jquery-animation-detect-if-animating) rather than "rolling your own". – freedomn-m Mar 31 '22 at 14:32

0 Answers0