JSFiddle - React, Tailwind, and code Playground
by Palpatim
HTML
<div class="accordion accordion1 init">
<section>
<h1>Header 1 <span>-</span></h1>
<div>
<p>Content for section</p>
</div>
</section>
<section>
<h1>Header 2 <span>-</span></h1>
<div>
<p>Content for section</p>
</div>
</section>
<section>
<h1>Header 3 <span>-</span></h1>
<div>
<p>Content for section</p>
</div>
</section>
</div>
<button id="closeAll1">Close all in 1</button>
<p> </p>
<p> </p>
<div class="accordion accordion2">
<section>
<h1>Header 1 <span>-</span></h1>
<div>
<p>Content for section</p>
</div>
</section>
<section>
<h1>Header 2 <span>-</span></h1>
<div>
<p>Content for section</p>
</div>
</section>
<section>
<h1>Header 3 <span>-</span></h1>
<div>
<p>Content for section</p>
</div>
</section>
</div>
<button id="closeAll2">Close all in 2</button>
CSS
body {
font-size: 18px;
}
section div {
max-height: 100px;
overflow: hidden;
}
section.hidden div {
max-height: 0;
}
section h1 {
background: #999;
color: #fff;
padding: 1rem;
cursor: pointer;
}
.accordion section h1 span {
display: none;
}
.accordion.js section h1 span {
display: block;
float: right;
}
JavaScript
function Accordion(selector) {
var $accordion = $(selector).addClass('js').removeClass('init');
var $sections = $accordion.find('section');
var hideContent = function () {
$sections.addClass('hidden');
$accordion.find('h1 span').html('+');
};
this.hideContent = hideContent;
var openSectionByClickEvent = function (evt) {
hideContent();
var $parentSection = $(evt.target).closest('section');
var $span = $parentSection.find('h1 span');
$parentSection.toggleClass('hidden');
if ($parentSection.hasClass('hidden')) {
$span.html('+');
} else {
$span.html('-');
}
};
this.openSectionByClickEvent = openSectionByClickEvent;
hideContent();
$accordion.click('h1, span', openSectionByClickEvent);
}
(function () {
var a1 = new Accordion('.accordion1');
$('#closeAll1').click(a1.hideContent);
var a2 = new Accordion('.accordion2');
$('#closeAll2').click(a2.hideContent);
})();