While creating a sticky navbar that should be animated on scroll reducing its height I notice a strange bug.
When scroll small (for example only one tap on down arrow key), the nav is bouncing because the script seems to return 0 for scroll.
Here is the code :
window.onscroll = function() {
var scrollDiv = document.getElementById('dojo-nav');
if (window.scrollY > 0) {
scrollDiv.style.height = '50px';
} else {
scrollDiv.style.height = '200px';
}
};
body {
margin: 0;
}
#dojo-nav {
transition: all 0.2s ease-in;
}
<div id="dojo-nav" style="position:sticky;top:0px;background: violet;height: 200px;"></div>
<div style="height:50vh;background-color: cyan;"></div>
<div style="height:100vh;background-color: orange;"></div>
Is there anybody who can solved this issue without setting position fixed and navbar spacer or same height ?
3
Answers
To understand what is going on, I created this snippet from your code. I wrapped the
#dojo-nav
in adiv
. The sitcky positionning is applied to the wrapper but the height change is still applied to the#nav-dojo
element :In the above snippet, you see that the fact the height of the element is changed on scroll creates a white space when you scroll less than 150px.
In your code, it makes the height of the page change from the top so
window.scrollY
equals 0 again. This is what makes your header go back to it’s inital height.The
sticky
doesn’t work here becausewindow.scrollY
changes on the sticky DIV’s height changes.With
fixed
window.scrollY
is stable thus no the jittering.Also you don’t need to set styles in JS, use a CSS variable to change CSS rule values dynamically:
PLEASE ANSWER MY POST
Cek my post