Exercise: Creating an Accordion Menu with Vanilla JavaScript
An accordion menu is a great way to organize and present content in a compact format. It allows users to expand and collapse sections of content by clicking on headers, making it easier to navigate large amounts of information. In this blog post, we’ll walk through the process of creating a simple accordion menu using vanilla JavaScript, HTML, and CSS.
What is an Accordion Menu?
An accordion menu is a user interface component that consists of multiple sections. Each section has a header (or button), and clicking on the header toggles the visibility of the content panel associated with it. This allows users to view only the sections they are interested in, while keeping the rest of the content hidden.
Implementing the Accordion Menu
Here’s the JavaScript code to create an accordion menu:
document.addEventListener("DOMContentLoaded", function() {
const accordions = document.querySelectorAll(".accordion");
accordions.forEach(accordion => {
accordion.addEventListener("click", function() {
this.classList.toggle("active");
const panel = this.nextElementSibling;
if (panel.style.maxHeight) {
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
});
});
});
Code Explanation
HTML Structure
Here’s an example of the HTML structure that works with the JavaScript code:
领英推荐
<button class="accordion">Section 1</button>
<div class="panel">
<p>Section 1 content...</p>
</div>
<button class="accordion">Section 2</button>
<div class="panel">
<p>Section 2 content...</p>
</div>
CSS Styling
To style the accordion and panel, you can use the following CSS:
.accordion {
background-color: #eee;
cursor: pointer;
padding: 10px;
width: 100%;
border: none;
text-align: left;
outline: none;
transition: background-color 0.3s ease;
}
.accordion.active, .accordion:hover {
background-color: #ccc;
}
.panel {
padding: 0 10px;
background-color: white;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
}
CSS Explanation
How It Works
Conclusion
Creating an accordion menu with vanilla JavaScript is a straightforward task that can greatly enhance the usability of your website. This implementation is lightweight, easy to customize, and perfect for organizing content in a compact and interactive way. You can use this accordion menu in a variety of contexts, such as FAQs, content navigation, or collapsible sections in a single-page application.