DEV Community

Cover image for Navbar scroll animation based on scroll direction(toggle navbar when user scroll up or down)

Posted on • Updated on

Navbar scroll animation based on scroll direction(toggle navbar when user scroll up or down)

In this article, I will show you, how you can create navbar which shows when you scroll up.

Live demo link:-
Github Repo link:-

First you need to create 3 pages,

touch index.html style.scss app.js

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Toggle navbar</title>
    <link rel="stylesheet" href="./style.css" />
    <nav class="nav">
      <div class="nav__container">
        <div class="nav__logo">Navbar</div>
        <ul class="nav__menu">
          <li><a href="#">Home</a></li>
          <li><a href="#">About</a></li>
          <li><a href="#">Blogs</a></li>
          <li><a href="#">Contact us</a></li>

    <section>lorem3000 (and then press enter) </section>

    <script src="./app.js"></script>

Enter fullscreen mode Exit fullscreen mode
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;

body {
  overflow-x: hidden;
  max-width: 100vw;

.flex {
  display: flex;
  align-items: center;
  justify-content: space-between;

.nav {
  background-color: rgb(9, 190, 190);
  box-shadow: 0px 0px 5px silver;
  padding: 10px 0px;
  position: fixed;
  width: 100vw;
  top: -10%;
  opacity: 0;
  visibility: hidden;
  pointer-events: none;
  transition: all 0.3s ease-in;

  &.active__menu {
    top: 0%;
    opacity: 1;
    visibility: visible;
    pointer-events: visible;

  &__container {
    width: 90%;
    margin: auto;
    @extend .flex;

  &__logo {
    font-size: 2rem;
    font-weight: bold;

  &__menu {
    @extend .flex;
    list-style: none;

    li {
      a {
        color: black;
        text-decoration: none;
        margin-right: 10px;
        font-weight: 600;

section {
  width: 90%;
  margin: 8rem auto 2rem auto;

Enter fullscreen mode Exit fullscreen mode
// Grab nav element from the dom
const nav = document.querySelector("nav");

// Creating variales
let scroll_position = 30;
let scroll_direction;

// Show Navbar when dom loads

// Create an scroll event listener
window.addEventListener("scroll", () => {
  scroll_direction =
    document.body.getBoundingClientRect().top > scroll_position ? "up" : "down";
  scroll_position = document.body.getBoundingClientRect().top;

  if (scroll_direction === "up") {
    // If you are scrolling up, then add active menu class
  } else {
    // If you Scrolling down, remove the active menu class

//Create Variables outside the scroll event listener
Enter fullscreen mode Exit fullscreen mode

Top comments (0)