I have a div which collapses on a button click. Code as follows:
const collapse = () => {
const title = document.getElementById('title');
title.classList.add('d-none');
const out = document.getElementById('out');
out.classList.add('collapse');
}
.out {
width: 200px;
background-color: grey;
display: flex;
justify-content: space-between;
}
.d-none {
display: none;
}
.collapse {
width: 65px;
}
.btn {
width: 65px;
}
<div id='out' class='out'>
<span id='title'>Title</span>
<button class='btn' onclick='collapse()'>Collapse</button>
</div>
I'd like to add a transition effect, so that the div would collapse smoothly, the button would move smoothly to the left end with div collapse. How can I do that?
EDIT I may have misunderstood what your intended outcome is. If you comment on here what you'd like it to do, I can make it more correctly align. :)
I've added an example with what you have, but I'd recommend just adding and removing a class based on the state.
Basically, you just toggle the 'collapse' classname, and add transition properties to the div class, as well as the collapse class. You can see the code below:
const collapse = () => {
const out = document.getElementById('out');
// We only have to toggle the collapse class
out.classList.toggle('collapse');
}
.out {
width: 200px;
background-color: grey;
display: inline-block;
/* This transition happens when the collapse is removed */
transition: all 300ms ease-in-out;
}
.d-none {
height: 0;
}
.collapse {
width: 0;
/* This transition happens when the collapse class is added */
transition: all 300ms ease-in-out;
}
.btn {
width: auto;
margin-left: -5px;
}
<div id='out' class='out'>
<span id='title'>Title</span>
</div>
<button class='btn' onclick='collapse()'>Collapse</button>