Use jquery + animation according to the scroll height to change the header menu background color, but encounter problems

$(window).scroll(function() {
  if ($(this).scrollTop() > 0) {
    $(".header-menu-layout").css("background-color", "white");
    $(".header-menu-layout").animate({
      backgroundColor: "white"
    }, 300);
  }

  if ($(this).scrollTop() == 0) {
    $(".header-menu-layout").css("background-color", "transparent");
    $(".header-menu-layout").stop().animate({
      backgroundColor: "transparent"
    }, 300);
  }
});

when the height is greater than 1px and above,
will run animate, and the background will turn white.
but find a fatal problem
is that he will run the first paragraph of fucntion
which causes the scrolling event to stop before he can produce animation.
because you monitor every time you scroll?
the method I refer to is
https://www.spectacles.com/
, but it doesn"t seem to be the case.


when the Scroll occurs (not stopped), the first function is executed continuously, and its animation has a delay of 300ms. Each scrolling of the px causes the first function to execute again, and the antmation is triggered. The execution of the latter animation terminates the previous animation execution. When scrolling stops, the last animation is executed.

to achieve your goal, you can simply set a bool variable, determine whether it is true when scrolling occurs, and ensure that it is executed only once. When the page returns to its original position, it is set to false.

var isScrollAnimationFired = false;
$(window).scroll(function() {
  if ($(this).scrollTop() > 0) {
    $('.header-menu-layout').css('background-color', 'white');
    if(!isScrollAnimationFired) {
      $('.header-menu-layout').animate({
        backgroundColor: 'white'
      }, 300);
      isScrollAnimationFired = true;
    }
  }

  if ($(this).scrollTop() == 0) {
    $('.header-menu-layout').css('background-color', 'transparent');
    $('.header-menu-layout').stop().animate({
      backgroundColor: 'transparent'
    }, 300);
    isScrollAnimationFired = false;
  }
});
Menu