A simple HTML code was created with the full pen accessible here.
<div class="center">
<div class="menu">
<div class="item">
<button class="accordionBtn"><i class="fas fa-user"></i> Profile</button>
<div class="accordionContent">
<a href="#">Posts</a>
<a href="#">Pictures</a>
</div>
</div>
<div class="item">
<button class="accordionBtn"><i class="far fa-envelope"></i> Message</button>
<div class="accordionContent">
<a href="#">New</a>
<a href="#">Sent</a>
<a href="#">Spam</a>
</div>
</div>
<div class="item">
<button class="accordionBtn"><i class="fas fa-cog"></i> Settings</button>
<div class="accordionContent">
<a href="#">Password</a>
<a href="#">Language</a>
</div>
</div>
<div class="item">
<button class="accordionBtn"><i class="fas fa-sign-out-alt"></i> Sign out</button>
</div>
</div>
</div>
Additionally, JavaScript was used to toggle the respective accordion content:
const btns = document.querySelectorAll(".accordionBtn");
btns.forEach((btn) => {
btn.addEventListener("click", () => {
const sibling = btn.nextElementSibling;
if (sibling) {
sibling.classList.toggle("show");
}
});
});
When clicking on an accordion, it was desired for others to collapse. The following solution was implemented:
const btns = document.querySelectorAll(".accordionBtn");
const acc_contents = document.querySelectorAll(".accordionContent");
btns.forEach((btn) => {
btn.addEventListener("click", () => {
// new
acc_contents.forEach(acc => {
if(acc.classList.contains('show')) {
acc.classList.remove('show');
}
})
const sibling = btn.nextElementSibling;
if (sibling) {
sibling.classList.toggle("show");
}
});
});
However, this implementation disabled the toggle functionality. Assistance from anyone who can provide a solution would be greatly appreciated.