简体   繁体   中英

Fixed navbar that disappears when not on top and not scrolling isn't working as intended

I'm trying to build a navbar that displays normally when window.pageYOffset is less than 500, otherwise it would show while scrolling and hide 1200 milliseconds after user stops scrolling. Here's my CodePen https://codepen.io/youssefwael/pen/LYZKmom and at the bottom of the js you'll see the part I'm stuck at

document.addEventListener("scroll", () => {
    nav.style.display = "block";
    clearTimeout(hide);
    if (window.pageYOffset > 500) {
        const hide = setTimeout(() => {
            nav.style.display = "none";
        }, 1200);
    }
});

What am I doing wrong here? I've been trying to figure this out since yesterday because I feel like it really should work. Currently if you scroll up and down quickly it bugs out the timeout. Also, scrolling from the bottom up quickly causes the navbar to disappear at the top, which shouldn't happen. I thought adding the clearTimeout() would fix both of these, but it doesn't.

Thanks in advance.

For the scroll behaviour I have made some changes in your event Listener Here is a simplified version:

const myNavbar = document.querySelector(".navbar__menu");

document.addEventListener("scroll", () => {
    if (window.pageYOffset > 500) {
      myNavbar.classList.add("navbar-fixed");
      myNavbar.classList.remove("navbar-relative");
    }
  else if (window.pageYOffset < 500) {
      myNavbar.classList.add("navbar-relative");
    myNavbar.classList.remove("navbar-fixed");
    }
});

you can simply use styling relative or fixed on navbar based on these classes. There is also a bug in your code because the hide variable is not accessible outside its scope

I found the problem so I'll post it here for future dwellers who may come across the same issue. All I had to do is declare hide outside the function and now it works wonders.

let hideNav;
document.addEventListener("scroll", () => {
    nav.style.display = "block";
    clearTimeout(hideNav);
    if (window.pageYOffset > 500) {
        hideNav = setTimeout(() => {
            nav.style.display = "none";
        }, 1200);
    }
});

PS: I don't know how to close this question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM