Skip to main content

Implement a custom Accordion Component

You are required to implement a custom accordion component.

Solution

<section class="accordion">
<div class="accordion-item">
<div class="accordion-header">Section 1</div>
<div class="accordion-content">Content for section 1.</div>
</div>
<div class="accordion-item">
<div class="accordion-header">Section 2</div>
<div class="accordion-content">Content for section 2.</div>
</div>
<div class="accordion-item">
<div class="accordion-header">Section 3</div>
<div class="accordion-content">Content for section 3.</div>
</div>
</section>
const accordionHeaders = document.querySelectorAll(".accordion-header");

accordionHeaders.forEach((header) => {
header.addEventListener("click", function () {
// Toggle the active class on the header
this.classList.toggle("active");

// Get the associated content element
const content = this.nextElementSibling;

// Toggle the display of the content
if (content.style.display === "block") {
content.style.display = "none";
} else {
content.style.display = "block";
}
});
});
.accordion {
width: 100%;
max-width: 600px;
margin: 0 auto;
border: 1px solid #ccc;
border-radius: 5px;
overflow: hidden;
}

.accordion-item {
border-bottom: 1px solid #ccc;
}

.accordion-item:last-child {
border-bottom: none;
}

.accordion-header {
padding: 15px;
background-color: #f1f1f1;
cursor: pointer;
font-weight: bold;
}

.accordion-content {
display: none;
padding: 15px;
background-color: #fff;
}

Demo