It would be great if you could add a buffer to the ‘.slide-up’ class being add/removed after the ‘scroll up after (px)’ height on desktop.
On very small scrolls the header jumps up and down.
Here is a temp workaround:
- Keep the ‘sticky’ enabled in the header settings.
- Do not set a height for ‘scroll up after (px)’
- Use this code snippet in your header:
document.addEventListener('DOMContentLoaded', function() {
var header = document.querySelector('header');
var lastScrollTop = window.pageYOffset || document.documentElement.scrollTop;
var slidingTimeout;
var applyBuffer = window.innerWidth >= 992;
function updateApplyBuffer() {
applyBuffer = window.innerWidth >= 992;
}
window.addEventListener('resize', updateApplyBuffer);
window.addEventListener('scroll', function() {
var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
var delta = scrollTop - lastScrollTop;
if (scrollTop < 200) {
// Always show the header before 200px
if (header.classList.contains('slide-up')) {
header.classList.remove('slide-up');
header.classList.add('sliding');
clearTimeout(slidingTimeout);
slidingTimeout = setTimeout(function() {
header.classList.remove('sliding');
}, 400);
}
} else {
if (applyBuffer) {
if (delta > 2) {
// Scrolling down with buffer
if (!header.classList.contains('slide-up')) {
header.classList.add('slide-up', 'sliding');
clearTimeout(slidingTimeout);
slidingTimeout = setTimeout(function() {
header.classList.remove('sliding');
}, 400);
}
} else if (delta < -2) {
// Scrolling up with buffer
if (header.classList.contains('slide-up')) {
header.classList.remove('slide-up');
header.classList.add('sliding');
clearTimeout(slidingTimeout);
slidingTimeout = setTimeout(function() {
header.classList.remove('sliding');
}, 400);
}
}
// Do nothing if delta is between -5 and 5 to prevent jitter
} else {
if (delta > 0) {
// Scrolling down without buffer
if (!header.classList.contains('slide-up')) {
header.classList.add('slide-up', 'sliding');
clearTimeout(slidingTimeout);
slidingTimeout = setTimeout(function() {
header.classList.remove('sliding');
}, 400);
}
} else if (delta < 0) {
// Scrolling up without buffer
if (header.classList.contains('slide-up')) {
header.classList.remove('slide-up');
header.classList.add('sliding');
clearTimeout(slidingTimeout);
slidingTimeout = setTimeout(function() {
header.classList.remove('sliding');
}, 400);
}
}
// No buffer applied; header reacts immediately to scroll direction
}
}
lastScrollTop = scrollTop;
});
});
In this code the header slides up after 200px. Then a 2px buffer has been set to scroll up/down to toggle the ‘.slide-up’ class that gets added to the header element. It also keeps the functionality of adding the ‘.sliding’ class to the header when the header is transitioning, in my case 400ms. The buffer doesn’t apply to screen widths below 992px.
This fixes the jittering issue.