DEV Community

Cover image for Slide Down Menu on Scroll
Chris Bongers
Chris Bongers

Posted on • Originally published at


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="" target="_blank">Blog</a>
  <a href="" target="_blank">Twitter</a>
  <a href="#" target="_blank">Facebook</a>

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

  A lot of content here...
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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) { = '0';
  } else { = '-50px';
Enter fullscreen mode Exit fullscreen mode

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

Top comments (1)

fredskatar profile image
Fredrik Skåtar

Hi Chris, this is fantastic, it finally solved a problem I have been fighting with for a while. Thank you!

However, I have another issue that came up: From that menu, I have some drop-downs that have there own scroll, based on an "overflow:auto". These drop-downs don't affect the slide-up, but maybe they could if I address them in the JS. I have tried to replace document and body with their IDs but it's simply above my knowledge. Would you have an idea?

Here is the page I refer to:

I reckon, others might have the same issue...


Need a better mental model for async/await?

Check out this classic DEV post on the subject.

⭐️🎀 JavaScript Visualized: Promises & Async/Await

async await