0

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?

jialeee17
  • 601
  • 2
  • 7
  • 12

3 Answers3

0

Because you are switching between display: block; and display: none;. It doesn't trigger the transition.

Instead you can hide/show by manipulating the height, opacity or width from 0 to a set value. There are most likely even more approaches other than height, opacity and width. The transition would then be triggered from value 0 to value x.

E_net4
  • 27,810
  • 13
  • 101
  • 139
Daly
  • 134
  • 5
0

replacement Display property with Visibility can help you. visibility : hidden => visible.

Ahmad MRF
  • 1,346
  • 1
  • 6
  • 16
0

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.

Osama Khawar
  • 74
  • 1
  • 6