Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if/else statement with setTimeout causes flicker

Tags:

javascript

I'm displaying an element on scrolling down and hiding it when scrolling up again. Without using setTimeout, this works just as expected. However, using setTimeout causes the 'display' class to be added and removed in short intervals when scrolling down. How can I avoid this while keeping the delay?

onscroll = function() {
  var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  if (scrollTop > 110) {
    menuButton.classList.add('display');
  } else {
    setTimeout(function() {
      menuButton.classList.remove('display');
    }, 400);
  }
}
like image 684
Georg Avatar asked Sep 02 '25 04:09

Georg


1 Answers

The timeout was still firing from earlier events. Here is my fix:

onscroll = function() {
  var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  var timer;
  if (scrollTop > 110) {
    window.clearTimeout(timer);
    menuButton.classList.add('display');
  } else {
    timer = window.setTimeout(function() {
          menuButton.classList.remove('display');
      }, 400);
  }
}
like image 84
Georg Avatar answered Sep 05 '25 01:09

Georg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!