JSFiddle - React, Tailwind, and code Playground
by cokolox
HTML
<div id="accordion-container">
<div class="accordion">
<div class="accordion-header">
<h3>Accordion 1</h3>
</div>
<div class="accordion-body">
<div class="accordion-content">
<p>Content for accordion 1.</p>
<p>Content for accordion 1.</p>
<p>Content for accordion 1.</p>
</div>
</div>
</div>
<div class="accordion">
<div class="accordion-header">
<h3>Accordion 2</h3>
</div>
<div class="accordion-body">
<div class="accordion-content">
<p>Content for accordion 2.</p>
<p>Content for accordion 2.</p>
<p>Content for accordion 2.</p>
</div>
</div>
</div>
</div>
CSS
/* Basic styles for the accordion */
.accordion {
border: 1px solid #ccc;
margin: 10px 0;
}
.accordion-header {
padding: 10px;
background-color: #f7f7f7;
cursor: pointer;
user-select: none;
}
.accordion-body {
overflow: hidden;
display: none; /* Hidden by default */
border-top: 1px solid #ccc;
}
.accordion-content {
padding: 0 20px
}
JavaScript
// Animation Utilities
function slideUp(target, duration = 300) {
target.style.transitionProperty = 'height, margin, padding';
target.style.transitionDuration = `${duration}ms`;
target.style.boxSizing = 'border-box';
target.style.height = `${target.offsetHeight}px`; // Set current height
target.offsetHeight; // Force repaint
target.style.overflow = 'hidden';
target.style.height = 0;
target.style.paddingTop = 0;
target.style.paddingBottom = 0;
target.style.marginTop = 0;
target.style.marginBottom = 0;
window.setTimeout(() => {
target.style.display = 'none';
target.style.removeProperty('height');
target.style.removeProperty('padding-top');
target.style.removeProperty('padding-bottom');
target.style.removeProperty('margin-top');
target.style.removeProperty('margin-bottom');
target.style.removeProperty('overflow');
target.style.removeProperty('transition-duration');
target.style.removeProperty('transition-property');
}, duration);
}
function slideDown(target, duration = 300) {
target.style.removeProperty('display');
let display = window.getComputedStyle(target).display;
if (display === 'none') display = 'block';
target.style.display = display;
const height = target.offsetHeight;
target.style.overflow = 'hidden';
target.style.height = 0;
target.style.paddingTop = 0;
target.style.paddingBottom = 0;
target.style.marginTop = 0;
target.style.marginBottom = 0;
target.offsetHeight; // Force repaint
target.style.boxSizing = 'border-box';
target.style.transitionProperty = 'height, margin, padding';
target.style.transitionDuration = `${duration}ms`;
target.style.height = `${height}px`;
window.setTimeout(() => {
target.style.removeProperty('height');
target.style.removeProperty('overflow');
target.style.removeProperty('transition-duration');
...