JSFiddle - React, Tailwind, and code Playground
by disfated
HTML
<button data-slidetoggle="#box1">Toggle Box 1</button>
<div id="box1">
<ul>
<li>list item</li>
<li>list item</li>
<li>list item</li>
<li>list item</li>
<li>list item</li>
<li>list item</li>
<li>list item</li>
<li>list item</li>
<li>list item</li>
<li>list item</li>
<li>list item</li>
<li>list item</li>
</ul>
</div>
CSS
#box1,
#box2 {
overflow: hidden;
margin-bottom: 20px;
background-color: #4f88ff;
transition: height 0.5s;
}
ul {
column-width: 10ch;
column-gap: calc(1ch + 1.6em);
margin-top: 0;
margin-bottom: 0;
}
JavaScript
function slidetoggle() {
document.querySelectorAll(this.getAttribute('data-slidetoggle')).forEach(el => {
el.style.height = (isCollapsed || noHeightSet ? sh : 0) + "px";
if (noHeightSet) return slidetoggle.call(this);
});
}
for (const button of document.querySelectorAll('[data-slidetoggle]')) {
const wrap = document.querySelector(button.dataset.slidetoggle)
button.addEventListener('click', (e) => {
e.preventDefault()
const ch = wrap.clientHeight
const sh = wrap.scrollHeight
const is_collapsed = !ch
const no_height_set = !wrap.style.height
wrap.style.height = (is_collapsed || no_height_set ? sh : 0) + 'px'
if (no_height_set) return slidetoggle.call(wrap)
})
}