Subscribe

Slide Down Menu on Scroll

✍️

Today we make a slide down menu with CSS and JavaScript

12 Jun, 2020 Β· 2 min read

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 to 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 actual magic, that comes down to JavaScript.

const 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.

See the Pen Slide Down Menu on Scroll by Chris Bongers (@rebelchris) 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

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next πŸ“–

Show and hide a header based on scroll direction

9 Jan, 2022 Β· 5 min read

Show and hide a header based on scroll direction

How I made a no-div playground in Vanilla JavaScript

28 Dec, 2020 Β· 9 min read

How I made a no-div playground in Vanilla JavaScript

Join 2099 devs and subscribe to my newsletter