I have this code that makes my navbar hide when scrolling down and appear when scrolling up. Currently it hides instantly when scrolling down. I would like to change this behavior to hide after scrolling 200px.
Thank you for your help!
var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
if (prevScrollpos > currentScrollPos) {
document.getElementById("custom-navbar").style.top = "0";
} else {
document.getElementById("custom-navbar").style.top = "-73px";
}
prevScrollpos = currentScrollPos;
}
Currently every time you scroll the variable prevScrollpos
is updated. If you change that behavior to only update when scrolling up you'll be able to use that variable to measure the 200px scroll you want.
var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
if (prevScrollpos > currentScrollPos) {
document.getElementById("custom-navbar").style.top = "0";
prevScrollpos = currentScrollPos;
} else if (currentScrollPos > prevScrollpos + 200){
document.getElementById("custom-navbar").style.top = "-73px";
prevScrollpos = currentScrollPos;
}
}
You really want to clean up this code though. For example prevScrollpos
has a lower case p
while currentScrollPos
has upper case P
which is inconsistent and will lead to errors when you mistype later. Also the way this is structured you'll constantly make style changes to your navbar while scrolling. Every time you scroll up you overwrite "0"
with "0"
, and the same is true for every time you scroll 200px down.
A better way to structure this would be to introduce a new Boolean variable that keeps track if the navbar is hidden or not. This way you can make sure you only change style when you actually want a change.