Slide Down Menu on Scroll

— 4 minute 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 permalink

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

CSS Structure permalink

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 permalink

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';

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! permalink

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