Reputation: 1014
I'm trying to get a square to 'fold out' on click of a button -- kind of like a drop-down.
Right now I have this, but it doesn't seem to do anything...
function toggle() {
let classList = document.getElementById('box').classList;
if (classList.contains('expand')) {
classList.remove('expand');
classList.add('retract');
} else if (classList.contains('retract')) {
classList.remove('retract');
classList.add('expand');
}
}
@keyframes anim {
0%: {
visibility: hidden;
}
1%: {
visibility: visible;
max-height: 0px;
}
100%: {
visibility: visible;
max-height: 100px; /* or something bigger than we'll 'ever need' */
}
}
.expand .retract {
animation-name: anim;
animation-duration: 500ms;
animation-iteration-count: 1;
}
.expand {
animation-fill-mode: forwards;
}
.retract {
animation-direction: reverse;
animation-fill-mode: backwards;
}
#box {
background-color: red;
height: 0px;
visibility: hidden;
width: 50px;
}
<button onclick="toggle()">toggle</button>
<div id="box"></div>
Note, that I need to have visibility: hidden
here!
How can I achieve this?
Upvotes: 0
Views: 372
Reputation:
OK, your problem is solved. This tryit from W3Schools helped me a lot. I didn't need two class names. Also, as @tao said, there is no point in animating visibility
(look at the comments below). Here is the CodePen pen with this code. I guess this is what you want, am I right?
const toggle = () => box?.classList.toggle('expand')
#box.expand {
height: 100px;
}
#box {
width: 50px;
height: 0;
overflow: hidden;
background: red;
transition: height 1s;
}
<button onclick="toggle()">toggle</button>
<div id="box"></div>
Upvotes: 1