Search code examples
htmlcsstoggletransition

Why is transition property not working in this case?


I'm creating a hamburger menu and I'm using JavaScript to handle the ON and OFF of the menu. Here's how my code looks like:

const hamburger_menu = document.querySelector('.hamburger-menu');
const side_nav = document.querySelector('.side-nav');

hamburger_menu.addEventListener('click', () => {
    side_nav.classList.toggle('open');
})

When the hamburger menu is clicked, the script will toggle the 'open' class on the hidden menu. I want the menu to have a transition effect when appearing. Here's how my SCSS looks like:

.side-nav {
    background: $black;
    display: none;
    padding: 5rem;
    position: absolute;
    top: 10.4rem;
    right: 0;
    bottom: -1.6rem;
    left: 0;
    opacity: 0;
    transition: all .3s ease;
    z-index: 100;

    &.open {
        display: block;
        opacity: 1;
    }
}

Somehow the transition effect is not working. Is there anyone knows the reason?


Solution

  • Transition will never work on display property. It works on properties like width, height, opacity etc. In your particular case, what you can do is, use height or width to control this animation. If your sidebar will appear from the left then you will need to set the initial width to 0 and then set the width to the actual width on click. Like this:

    .side_nav { 
      width: 0;
      transition: width 1s;
     
      &.open { 
        width: 200px; 
      }
     }

    Now when the open class will attach to your hamburger, it will animate the width.