Slide Down Menu on Scroll

Ever wondered how to make a menu that appears as soon as you scrolled a bit? Today we are going to create one like that. It will slide in from the top, the moment we scroll. And hide once we scrolled back to the top.

HTML Structure

<div id="navbar">
  <a href="https://daily-dev-tips.com/" target="_blank">Blog</a>
  <a href="https://twitter.com/DailyDevTips1" target="_blank">Twitter</a>
  <a href="#" target="_blank">Facebook</a>
</div>

<div class="content">
  <h1>Please scroll down to see the menu</h1>

  A lot of content here...
</div>

CSS Structure

As for the menu we use the following CSS

#navbar {
  background-color: #3f3f37;
  position: fixed;
  top: -50px;
  width: 100%;
  display: flex;
  transition: top 0.3s;
  justify-content: space-around;
}
#navbar a {
  display: block;
  color: #878472;
  text-align: center;
  padding: 15px;
  text-decoration: none;
}
#navbar a:hover {
  background-color: #878472;
  color: #3f3f37;
}

We give the navbar a position: fixed so it will stay on the top; But start from a negative 50 pixels. This will make it hidden at first. The animation will happen because of transition: top 0.3s;.

Then we style the links inside, but nothing fancy going on there.

JavaScript magic

As for the true magic, that comes down to JavaScript.

var navbar = document.getElementById('navbar');
window.onscroll = function() {
  if (document.body.scrollTop > 25 || document.documentElement.scrollTop > 25) {
    navbar.style.top = '0';
  } else {
    navbar.style.top = '-50px';
  }
};

We first define our navbar element. Then we start a scroll listener and check if we scrolled more than 25 pixels. If yes, we set the top of our navbar to 0. Else we will hide it again.

See it in action on this Codepen.

View on Codepen.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Learn Something New Everyday,
Connect With The Best Developers!

Sign Up Now!

& 500k+ others use Hashnode actively.

No Comments Yet