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

  1. Event Listener for DOMContentLoaded:
    • The script starts by adding an event listener for the DOMContentLoaded event. This ensures that the script runs after the entire HTML document has been loaded and parsed, making all DOM elements available for manipulation.
  2. Selecting Accordion Elements:
    • const accordions = document.querySelectorAll(".accordion");: This selects all elements with the class accordion and stores them in a NodeList. Each of these elements will serve as a button to toggle the visibility of its associated panel.
  3. Adding Click Event Listeners:
    • accordions.forEach(accordion => { ... });: This loops through each accordion element and adds an event listener for the click event.
    • Inside the event listener:
      • this.classList.toggle("active");: When an accordion is clicked, the active class is toggled on the clicked element. This class can be used to change the appearance of the active accordion (e.g., changing the background color).
      • const panel = this.nextElementSibling;: This selects the next sibling element of the clicked accordion, which is the panel containing the content.
      • if (panel.style.maxHeight) { ... } else { ... }: This condition checks if the panel’s maxHeight style is set. If it is, the panel is currently expanded, so setting maxHeight to null collapses it. If it’s not set, the panel is expanded by setting maxHeight to its scrollHeight, which is the full height of the panel’s content.

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>
  • Accordion Buttons (.accordion):
    • Each button with the accordion class acts as a trigger to expand or collapse the corresponding panel below it.
  • Panels (.panel):
    • Each div with the panel class contains the content that is either shown or hidden when the corresponding accordion button is clicked.

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

  1. Accordion Button Styles (.accordion):
    • The accordion buttons are styled with a light background color (#eee), padding, and a transition effect for the background color when hovered or activated. They have no border and are aligned to the left.
  2. Active and Hover States (.accordion.active, .accordion:hover):
    • When an accordion button is active (clicked) or hovered over, its background color changes to a slightly darker shade (#ccc). This provides a visual cue to the user.
  3. Panel Styles (.panel):
    • The content panels are hidden by default with a max-height of 0 and overflow: hidden. When expanded, the max-height is dynamically set based on the content height, with a smooth transition effect (max-height 0.2s ease-out).

How It Works

  • When the page loads, the accordion buttons and panels are ready for interaction.
  • Clicking an accordion button toggles its active class and adjusts the max-height of the corresponding panel to either show or hide the content.
  • The smooth transition effect makes the accordion menu visually appealing and user-friendly.

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.