Creating an animated hamburger menu icon

Published in

on

Even little animation can improve the overall user experience. Why not add this magic potion to your menu icon too. In this tutorial I’m showing you codes and scripts to create an animated hamburger menu icon.

Before we get into HTML, CSS, and JavaScript. Here is a live demo:

First let’s create a div element in header section where you wish to locate this beautiful animated hamburger menu icon.

<div class="menu-btn">
    <div class="menu-btn-lines"></div>
</div>

Now divs are ready, but they are empty. Now add some CSS elements on it.

.menu-btn {
  align-items: center;
  cursor: pointer;
  display: flex;
  height: 48px;
  justify-content: center;
  transition: ease-in-out 200ms;
}
.menu-btn-lines {
  background: black;
  border-radius: 5px;
  height: 4px;
  transition: ease-in-out 200ms;
  width: 32px;
}
.menu-btn-lines::before,
.menu-btn-lines::after {
  background: black;
  border-radius: 5px;
  content: "";
  height: 4px;
  position: absolute;
  transition: ease-in-out 200ms;
  width: 32px;
}
.menu-btn-lines::before {
  transform: translateY(-8px);
}
.menu-btn-lines::after {
  transform: translateY(8px);
}
.menu-btn.active .menu-btn-lines {
  background: transparent;
}
.menu-btn.active .menu-btn-lines::before {
  transform: rotate(45deg);
}
.menu-btn.active .menu-btn-lines::after {
  transform: rotate(-45deg);
}

The CSS section is complete.

Now we need to add a function to make it animate when someone click on it.

As you can read the CSS, we have added .active class already to make it work when someone clicks on it, and when clicked again we have to remove it.

We can do this job in JavaScript very easily.

So here is the JavaScript code:

// Hamburger Menu Icon JS Code by AtulHost.com
const menuBtn = document.querySelector('.menu-btn');
let menuActive = false;
menuBtn.addEventListener('click', () => {
  if(!menuActive) {
    menuBtn.classList.add('active');
    menuActive = true;
  } else {
    menuBtn.classList.remove('active');
    menuActive = false;
  }
});

Now do a test run, it should work now.

You can modify this to match your theme design, size, and more.

Leave a Reply

Your email address will not be published. Required fields are marked *