As I develop a website, I have implemented a sticky header that shrinks after scrolling past the window height. I experimented with two versions - one using Vanilla-JS and another with jQuery. Both versions work fine, but the issue arises when the header starts flickering while slowly scrolling right to the point of transition. Hopefully, the gif provided makes it clear.
https://i.sstatic.net/HrhY2.gif
I have researched about possible problems related to the "sticky-position" property of the header but couldn't find any information regarding flickering at or near the transition point. I would prefer a solution using Vanilla-JS over jQuery since my familiarity is limited with the latter, but I am open to using jQuery if necessary.
Vanilla-JS Version:
function header() {
Y = window.pageYOffset;
active = window.innerHeight;
header = document.getElementById('header');
if (Y > active) {
header.classList.add("headerScrolled");
} else {
header.classList.remove("headerScrolled");
}
}
window.addEventListener('scroll', header);
.header {
width: 100vw;
position: sticky;
top: 0;
height: 15vh;
background-color: blue;
-webkit-transition: all 0.5s;
-moz-transition: all 0.5s;
transition: all 0.5s;
z-index: 9999;
}
.headerScrolled {
background-color: #fff;
height: 10vh;
-webkit-box-shadow: 0 3px 5px rgba(57, 63, 72, 0.2);
-moz-box-shadow: 0 3px 5px rgba(57, 63, 72, 0.2);
box-shadow: 0 3px 5px rgba(57, 63, 72, 0.2);
-webkit-transition: all 0.5s;
-moz-transition: all 0.5s;
transition: all 0.5s;
}
#s1 {
height: 100vh;
}
#s2 {
height: 100vh;
background-color: gold;
}
<div class="header" id="header">
<div class="navigation">
<a>Link</a>
<a>Link</a>
<a>Link</a>
</div>
</div>
<section id="s1">
</section>
<section id="s2">
</section>
jQuery version:
$(document).ready(function() {
$(window).scroll(function() {
if($(document).scrollTop() > 200) {
$('.header').addClass('headerScrolled');
}
else {
$('.header').removeClass('headerScrolled');
}
});
});
.header {
width: 100vw;
position: sticky;
top: 0;
height: 15vh;
background-color: blue;
-webkit-transition: all 0.5s;
-moz-transition: all 0.5s;
transition: all 0.5s;
z-index: 9999;
}
.headerScrolled {
background-color: #fff;
height: 10vh;
-webkit-box-shadow: 0 3px 5px rgba(57, 63, 72, 0.2);
-moz-box-shadow: 0 3px 5px rgba(57, 63, 72, 0.2);
box-shadow: 0 3px 5px rgba(57, 63, 72, 0.2);
-webkit-transition: all 0.5s;
-moz-transition: all 0.5s;
transition: all 0.5s;
}
#s1 {
height: 100vh;
}
#s2 {
height: 100vh;
background-color: gold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="header" id="header">
<div class="navigation">
<a>Link</a>
<a>Link</a>
<a>Link</a>
</div>
</div>
<section id="s1">
</section>
<section id="s2">
</section>