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?
CodePudding user response:
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 >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.