Javascript

Simple Accordion with JavaScript

Simple Accordion with JavaScript: Step-by-Step Guide

An accordion lets you hide and show sections of content by clicking on headers — great for FAQs, menus, or any collapsible content.


HTML Structure

Here’s a simple accordion with three items:

html
<div class="accordion">

<div class="accordion-item">
<button class="accordion-header">Section 1</button>
<div class="accordion-content">
<p>This is the content for section 1.</p>
</div>
</div>

<div class="accordion-item">
<button class="accordion-header">Section 2</button>
<div class="accordion-content">
<p>This is the content for section 2.</p>
</div>
</div>

<div class="accordion-item">
<button class="accordion-header">Section 3</button>
<div class="accordion-content">
<p>This is the content for section 3.</p>
</div>
</div>

</div>


CSS for Styling and Hiding Content

css
.accordion-header {
background-color: #007BFF;
color: white;
cursor: pointer;
padding: 15px;
border: none;
width: 100%;
text-align: left;
font-size: 16px;
outline: none;
transition: background-color 0.3s;
}

.accordion-header:hover {
background-color: #0056b3;
}

.accordion-content {
padding: 15px;
display: none; /* Hide by default */
background-color: #f1f1f1;
}

.accordion-content.show {
display: block; /* Show when active */
}


⚙️ JavaScript to Toggle Accordion Sections

js
// Select all accordion headers
const headers = document.querySelectorAll('.accordion-header');

headers.forEach(header => {
header.addEventListener('click', () => {
// Get the associated content panel (next sibling)
const content = header.nextElementSibling;

// Toggle the 'show' class on content
content.classList.toggle('show');

// Optionally, close other panels (only one open at a time)
headers.forEach(otherHeader => {
if (otherHeader !== header) {
otherHeader.nextElementSibling.classList.remove('show');
}
});
});
});


How It Works:

  • When you click a header button, the script toggles the .show class on the corresponding content panel.

  • The .show class changes the CSS display from none to block, making it visible.

  • The script also closes any other open accordion sections for a clean one-at-a-time effect.

Leave a Reply

Your email address will not be published. Required fields are marked *