Sticky Hide Navigation Bar

Sun Dec 30 2018

Hi, today we are going to show you how to create sticky navigation that can hide/show when user scrolled the page. If you realized, our website’s navigation works just like that and here we’re going to tell you how we did it using vanilla javascript.

First thing to do is to design your own navigation bar. Here’s our simple navigation code:

<div class="navbar">
  <div class="logo">
    <a href="#">ACOY.CO</a>
  </div>
  <div class="menu">
    <a href="#">HOME</a>
    <a href="#">SERVICES</a>
    <a href="#">BLOG</a>
  </div>
</div>

The main idea is to transform our navbar using translate CSS when user scroll down/up, we can detect the scroll event using onscroll event handler. This is our CSS for fixed navigation and how to hide it.

.navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 50px;
  display: flex;
  align-items: center;
  background: white;
  transition: all 0.5s;
}

.hide {
  transform: translate3D(0,-100%,0);
}

Alright, we already have the navigation and the way to hide it. Next thing to do is to detect whether our user scroll up or down. We use currentScroll to detect the whether the scroll going up or down by comparing it with the new scroll value.

const nav = document.querySelector('.navbar')

let scrollPosition = 0
window.onscroll = (e) => {
  const currentScroll = window.scrollY
  //   if scroll down at least 50px
  if(currentScroll > scrollPosition + 50) {
    scrollPosition = currentScroll
    nav.classList.add('hide')
  }
  //   else scroll up at least 50px
  else if(currentScroll < scrollPosition - 50){
    scrollPosition = currentScroll
    nav.classList.remove('hide')
  }
}

We use 50px as the threshold, so if users are not scrolling up/down by 50px then don’t change anything. This is done because we don’t want the navigation to show/hide really fast that can confuse the users.

That’s it! You have built your own navigation that can show/hide when user scroll, for the demo you can click here.