Search code examples
javascriptjqueryhtmlslidetoggle

slideToggle is animating the div up and down continuously


I am using slideToggle to make my header move with the page once scrollTop hit the 100. But once the scrollbar reaches to 100 and more, it keeps animating up and down for few moment. Here is my code:

$(window).scroll(function(){
   var ScrollTop    = $(window).scrollTop();
   if(ScrollTop>=100){
       $('#main_header').removeClass("relative");
       $('#main_header').addClass("fixed");
       $('#main_header').slideToggle("slow");
   }else if(ScrollTop<=99){
       $('#main_header').removeClass("fixed");
       $('#main_header').addClass("relative");
   }
});

please let me know what's wrong?


Solution

  • You are saying to the browser, whenever the user scrolls down the page, see how far they have travelled. If they have travelled more than 99, then slide that header, otherwise do some other class toggling.

    So let's say they scroll to 120, it will slide. Then they scroll down more to 140, it will slide. You have no check in place on whether it has already slid down, thus it will keep doing it. A simple approach would be to just add a boolean: -

    var toggled = false;
    
    $(window).scroll(function () {
       var ScrollTop = $(window).scrollTop();
    
       if (ScrollTop >= 100 && !toggled) {
           $('#main_header')
               .removeClass("relative")
               .addClass("fixed")
               .stop() // stop any prev animation
               .css('display', 'none') // force hide so it slides
               .slideToggle("slow");
    
           toggled = true; // won't enter again until set to false
       } else if (ScrollTop <= 99 && toggled) {
           $('#main_header').removeClass("fixed");
           $('#main_header').addClass("relative");
    
           toggled = false; // scrolled back up, can now slideToggle again!
       }
    });