JSFiddle - React, Tailwind, and code Playground
by LuckyCat
HTML
<div>
<h2 class="accordion">Main 1<i class="accordionArrow"></i></h2>
<h3 class="dropdown maxHeightZero">Submenu 1<i class="dropdownArrow"></i></h3>
<p class="content maxHeightZero">Hello there. We are exposed.</p>
</div>
<div>
<h2 class="accordion">Main 2<i class="accordionArrow"></i></h2>
<h3 class="dropdown maxHeightZero">Submenu 1<i class="dropdownArrow"></i></h3>
<p class="content maxHeightZero">Hello there. We are exposed again!</p>
</div>
<div>
<h2 class="accordion">Main 3<i class="accordionArrow"></i></h2>
<h3 class="dropdown maxHeightZero">Submenu 1<i class="dropdownArrow"></i></h3>
<p class="content maxHeightZero">Hello there. We are exposed thrice!</p>
</div>
CSS
body {
margin: auto;
width: 600px;
}
div {
margin: auto;
}
.accordion {
background-color: lightblue;
color: white;
padding: 3%;
cursor: pointer;
width: 300px;
height: 50px;
}
.accordion .accordionArrow {
border: solid white;
border-width: 0 3px 3px 0;
display: inline-block;
padding: 3px;
transform: rotate(45deg);
}
.dropdown {
color: lightblue;
padding-left: 3%;
cursor: pointer;
width: 300px;
overflow: hidden;
transition-duration: 0.2s;
}
.dropdown .dropdownArrow {
border: solid lightblue;
border-width: 0 3px 3px 0;
display: inline-block;
padding: 3px;
transform: rotate(45deg);
}
.content {
font-weight: bold;
transition: all 0.2s ease;
padding-left: 5%;
overflow: hidden;
}
.maxHeightZero {
max-height: 0;
}
JavaScript
document.querySelectorAll('.accordion').forEach((accordion) => accordion.addEventListener('click', function() {
//Get All possible hidden elements and loop over it.
document.querySelectorAll('.dropdown, .content').forEach((collapsible) => {
//If current element is the same is the next sibling element of the event target toggle the class. Otherwise add it.
if(collapsible === this.nextElementSibling) {
collapsible.classList.toggle('maxHeightZero');
}
else {
collapsible.classList.add('maxHeightZero');
}
});
}));
/*document.querySelectorAll('.dropdown').forEach((dropdown) => dropdown.addEventListener('click', function() {
//toggle the nextElementSibling
this.nextElementSibling.classList.toggle('maxHeightZero');
}));*/