Responsive Sliding Hamburge Menu System

Category: Javascript , Menu & Navigation | August 5, 2023
Author:TuxChad
Views Total:1,624 views
Official Page:Go to website
Last Update:August 5, 2023
License:MIT

Preview:

Responsive Sliding Hamburge Menu System

Description:

A responsive navigation system that transforms the regular horizontal navbar into a mobile-friendly hamburger menu when visiting on small screens.

How to use it:

1. Add the hamburger toggle button to your navbar.

<header>
  <nav class="navbar">
    <a href="#" class="logo">Logo</a>
    <ul class="nav-menu">
      <li class="nav-item">
        <a href="#" class="nav-link">Home</a>
      </li>
      <li class="nav-item">
        <a href="#" class="nav-link">About</a>
      </li>
      <li class="nav-item">
        <a href="#" class="nav-link">Work</a>
      </li>
      <li class="nav-item">
        <a href="#" class="nav-link">Contact</a>
      </li>
    </ul>
    <div class="hamburger">
      <span class="bar"></span>
      <span class="bar"></span>
      <span class="bar"></span>
    </div>
  </nav>
</header>

2. The basic CSS styles for the navbar.

li{
  list-style: none;
}
.navbar{
  height: 70px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 5%;
}
.nav-menu{
  display: flex;
  align-items: center;
}
.nav-branding{
  font-size: 2rem;
}
/* transition for links */
.nav-link{
  transition: 0.5s ease;
}
.nav-link:hover{
  color: dodgerblue;
}
.hamburger{
  display: none;
  cursor: pointer;
}
.bar{
  width: 25px;
  height: 3px;
  margin: 5px auto;
  -webkit-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
  background: white;
}
.nav-item{
  padding: 0 1.5rem;
}

3. Transform the navbar into a hamburger menu.

@media(max-width: 760px){
  .bar{
    display: block;
  }
  .hamburger{
    display: block;
  }
  .hamburger.active .bar:nth-child(2){
    opacity: 0;
  }
  .hamburger.active .bar:nth-child(1){
    transform: rotate(45deg) translateY(11.5px); 
  }  
  .hamburger.active .bar:nth-child(3){
    transform: rotate(-45deg) translateY(-11.5px); 
  }
  .nav-menu{
    position: fixed;
    right: -100%;
    top: 70px;
    flex-direction: column;
    width: 100%;
    text-align: center;
    background: black;
    transition: 0.3s;
  }
  .nav-item{
    padding: 1.5rem 0;
  }
  
  .nav-menu.active{
    right: 0;
  }
  
}

4. Open/close the hamburger menu by toggling CSS classes as follows:

const hamburger = document.querySelector(".hamburger")
const nav_menu = document.querySelector(".nav-menu")
hamburger.addEventListener("click",()=>{
  hamburger.classList.toggle("active");
  nav_menu.classList.toggle("active");
})
document.querySelectorAll(".nav-link").forEach(n => n.addEventListener("click", () => {
  hamburger.classList.remove("active");
  nav_menu.classList.remove("active");
}))

You Might Be Interested In:


Leave a Reply