Search code examples
javascriptcssecmascript-6sassfade

CSS Transition not working on class toggle JavaScript


Hello this is probably something easy and dumb, but I am not understanding why my css transition is not working on class toggle/remove/add function from JavaScript. I think I have a fundamental misunderstanding of css transitions and vanilla JS... I added a codepen. https://codepen.io/skwisgaar/pen/Yzygvqz

The class is added and removed as needed, but the transition is sharp with the transition in my css ignored. I don't think it's a problem with my css, I added a hover to test the transition without the add/remove in JS. It seems like this is the default behavior for JS? Is there something I need to add for the transition to work before or when the class is changed in JS? Any help is appreciated.

  const btn = document.querySelector('#show-hide');
  const pagenav = document.querySelector('#page-nav');
  const showhide = () => {
    if(pagenav.classList.contains('hidden')){
      pagenav.classList.remove('hidden');
    } else {
      pagenav.classList.add('hidden');
    } 
  }
  btn.onclick = showhide;

Here is my css:

#page-nav {
    opacity:1;
    position:fixed;
    bottom:0;
    width:100%;
    z-index:2;
    @include transition(opacity 500ms);
    &.hidden {
        opacity:0;
    }
    &:hover {
      opacity:0;
    }
}

Solution

  • You have a conflicting style for the class "hidden".

    CSS definition for hidden

    When the hidden class is applied it is set to display: none so it is essentially not included in the page layout and so cannot transition other properties.