Animated Menu Icon HTML CSS JS

 

Animated Menu Icon: Creating a Hamburger-to-X Animation

This project demonstrates a clean, modern UI element: a hamburger menu icon that smoothly transforms into an “X” when clicked. This type of animation provides visual feedback to users and adds a polished, interactive feel to websites and applications.

Let me walk you through how this animation works:

The project consists of three files:

  • HTML structure (index.html)
  • CSS styling and animation (styles.css)
  • JavaScript for interaction (main.js)

Key Components

HTML Structure

The HTML creates a simple container with the menu icon, which consists of three horizontal bars:

<div class="menu-icon" id="menuIcon">
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
</div>

CSS Animation

The CSS handles the appearance and transition effects:

.menu-icon {
width: 60px;
height: 60px;
background-color: white;
border-radius: 12px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
position: relative;
}
.menu-icon .bar {
width: 30px;
height: 3px;
background-color: #333;
position: absolute;
transition: all 0.3s ease;
}
/* Default position for three bars */
.menu-icon .bar:nth-child(1) {
transform: translateY(-8px);
}
.menu-icon .bar:nth-child(3) {
transform: translateY(8px);
}
/* Transformed position (X shape) */
.menu-icon.active .bar:nth-child(1) {
transform: rotate(45deg);
}
.menu-icon.active .bar:nth-child(2) {
opacity: 0;
}
.menu-icon.active .bar:nth-child(3) {
transform: rotate(-45deg);
}

JavaScript Interaction

The JavaScript applies the ‘active’ class when the icon is clicked:

const menuIcon = document.getElementById('menuIcon');
menuIcon.addEventListener('click', function() {
this.classList.toggle('active');
});

How the Animation Works

  1. Initial State: Three horizontal bars stacked vertically create the hamburger icon.
  2. Transition: When clicked, CSS transitions animate the transformation.
  3. Final State: The top bar rotates 45°, the middle bar fades out, and the bottom bar rotates -45°, forming an “X”.

This animation demonstrates several important front-end development concepts:

  • CSS transitions for smooth animations
  • Positioning elements with transforms
  • Using JavaScript event listeners
  • CSS selectors to target specific elements
  • Toggle functionality to switch between states

The clean, minimal design of this menu icon makes it versatile for various websites and applications. The smooth transition creates a satisfying user experience that subtly communicates the state change of the navigation menu.

Comments