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;
  }
});
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e65132-66113.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e65132-66113.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?