2

I'm trying to use the following two css classes to show/hide elements with transition effects-

    .hidden{
        opacity: 0;
        height: 0;
        overflow: hidden;
        visibility: hidden;
        transition: all 2s;
    }

    .shown{
        opacity: 1;
        visibility: visible;
        height: auto;
        transition: all 2s;
    }

    //JS code to toggle classes -
     $("#cancelLogin").click(function(){
         $('form.login').toggleClass("shown").toggleClass("hidden");
         $('.circles').toggleClass("concealed").toggleClass("shown");
     });

.shown works fine, but no transition happening while adding .hidden class. Any idea?

2
  • You aren't adding the hidden class. concealed is being added but it has no properties defined. Commented Jul 25, 2022 at 16:58
  • @Sarah that's a typo. I updated that. Commented Jul 25, 2022 at 17:22

1 Answer 1

1

Since you are using height: 0 on the hidden class, this will execute firstly and you won't see any transition during the hiding process. You can achieve this with multiple tricks and ways, like the CSS animation and do stuff in a certain order or add a delay to your height adjustment and make it execute after the transition happens.

You can use the setTimeout method to make this happen.

const div = document.querySelector("div")
const button = document.querySelector("button")

button.addEventListener("click", () => {
  if (div.classList.contains("hidden")) {
    div.classList.remove("hidden")
    div.classList.add("shown")
    div.style.height = 'auto'
  } else {
    div.classList.remove("shown")
    div.classList.add("hidden")

    setTimeout(() => {
      div.style.height = 0
    }, 1000)
  }
})
.div {
  transition: all 2s;
}

.hidden {
  opacity: 0;
  overflow: hidden;
  visibility: hidden;
}

.shown {
  opacity: 1;
  visibility: visible;
}
<div class="div">div</div>
<button>change visibility</button>

NOTE: To avoid CSS rule duplication it is always better to assign the transition to the element itself instead of classes which will be triggered based on different actions.

Sign up to request clarification or add additional context in comments.

1 Comment

Use transitionend event listener instead of setTimeout to make it less convoluted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.