We had a similar issue a while back and added a debounce mechanism/function (anti-flicker) to the scroll event listener. Debouncing will delay the execution of your scroll function until after a certain period of inactivity, so the function won't be called too frequently while scrolling.
a Slight change to your Javascript -
function debounce(func, wait) {
let timeout;
return function () {
const context = this;
const args = arguments;
const later = function () {
timeout = null;
func.apply(context, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
window.onscroll = debounce(function () {
scrollFunction();
}, 100);
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
document.getElementById("navContainer").style.padding = "20px 10px";
document.getElementById("logo").style.width = "200px";
} else {
document.getElementById("navContainer").style.padding = "40px 10px";
document.getElementById("logo").style.width = "400px";
}
}
You can see a working fiddle here -
Remove bouncing/flickering in scroll function[
^]
I have also tested it in your codepen, also works as expected.