DEV Community

Cover image for Animated hamburger menu
Manoj Rathod
Manoj Rathod

Posted on

Animated hamburger menu

Demo: - https://codepen.io/iammanojrathod/pen/RwLOZGE

HTML code: -

  <div class="button">
        <div class="btn"></div>
    </div>

Enter fullscreen mode Exit fullscreen mode

CSS code: -

*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
body{
    display: flex;
    justify-content: center;
    align-items: center;
    background: black;
    height: 100vh;
}
.button{
    width: 100px;
    height: 100px;
    border: 3px solid white;
    border-radius: 10px;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
}
.btn{
    width: 70px;
    height: 6px;
    background-color: white;
    border-radius: 10px;
    cursor: pointer;
    transition: all 0.5s ease;
}
.btn::before,
.btn::after{
    content: '';
    position: absolute;
    width: 70px;
    height: 6px;
    background-color: white;
    border-radius: 10px;
    transition: all 0.5s ease;
}
.btn::before{
    transform: translateY(-20px);
}
.btn::after{
    transform: translateY(20px);
}
.button.open .btn{
    background: transparent;
}
.button.open .btn::before{
    transform: rotate(45deg) translate(1px, -1px);
    background-color: red;
}
.button.open .btn::after{
    transform: rotate(-45deg) translate(-1px, -1px);
    background-color: red;
}
Enter fullscreen mode Exit fullscreen mode

JavaScript code: -

const button = document.querySelector('.button');

let menuOpen = false;

button.addEventListener('click', () => {
    if(!menuOpen){
        button.classList.add('open');
        menuOpen = true;
    } else {
        button.classList.remove('open');
        menuOpen = false;
    }
})
Enter fullscreen mode Exit fullscreen mode

Top comments (0)