mauzzamali mauzzamali - 5 months ago 11x
Javascript Question

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:

var ScrollTop = $(window).scrollTop();
}else if(ScrollTop<=99){

please let me know what's wrong?


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) {
           .stop() // stop any prev animation
           .css('display', 'none') // force hide so it slides

       toggled = true; // won't enter again until set to false
   } else if (ScrollTop <= 99 && toggled) {

       toggled = false; // scrolled back up, can now slideToggle again!