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);
}
}
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With