Get the 2024 Yearly Goals and Progress Tracker Notion Template for FREE!

How to Build an Accordion Menu 3 Simple Ways

SERIES: JavaScript Projects for Beginners

Updated on: Nov 1, 2023

10 mins read

Learn how to build a pure HTML accordion menu, and an interactive JavaScript accordion menu using two methods. Explore the power of accordions in web design.Create a cleaner and organized user experience effortlessly.

Welcome to the JavaScript Projects for Beginners Seriesstarstarstarstarstarstar . Throughout this series, we'll embark on a journey to explore a wide range of JavaScript projects. From simple mini-projects to more complex ones, we'll build various projects to help you master JavaScript fundamentals.

We will start this series with a simple project: Accordionsstarstarstarstarstarstar. Accordions are a great way to display content in a compact and organized manner. They allow users to access content without distraction selectively. We'll build three different but simple accordions using HTML, CSS, and JavaScript. Let's get started!

lady saying let's get started

Image from giphy.com
Discover your path in tech with Tech Career Roadmap! Free ebooks, courses, articles, & tools. From coding to no-code, start or switch careers effortlessly.

Discover your path in tech with Tech Career Roadmap! Free ebooks, courses, articles, & tools. From coding to no-code, start or switch careers effortlessly.

Prerequisites

Before we dive into creating accordions, I assume you understand HTML, CSS, and JavaScript. Familiarity with JavaScript DOM manipulation will be helpful.

Project Code and Live Demo:

You can access all the project code on my GitHub repository. Additionally, explore the live demo to interact with the finished projects.

What is an Accordion Menu?

A simple accordion menu is essentially a vertical list of headers or titles. When a user selects or clicks on an header, it reveals or conceals additional content associated with that header.

You've probably encountered accordions on Frequently Asked Questions (FAQ) pages, where they allow users to effortlessly scan through questions and selectively access answers without distraction.

A frequently asked questions accordion menu

A frequently asked questions accordion menu

Accordion menus are often used to display a substantial amount of information in a compact and organized manner. They can be used to present product descriptions, long content that needs organization, and any scenario where you want to show information in a user-friendly way.

Benefits of Using Accordions on a Website

Accordions offer several benefits, including:

  • Saving space on web pages: Accordions effectively save valuable space on web pages, allowing you to convey comprehensive information without overwhelming the layout.
  • Providing a clean and organized way to present content: They offer a clean and well-organized method to showcase content, ensuring visitors can easily access information that piques their interest.
  • Reducing clutter: By enabling content to expand or collapse, accordions reduce visual clutter, offering a polished and visually appealing browsing experience.
  • Enhancing user experience: Accordions improve user engagement by empowering visitors to focus on specific content sections, enhancing their overall interaction with your website.

How to Build an Accordion Menu

There are several ways to build an accordion, and we'll explore three simple ways on how to build an accordion. The first method uses the HTML <details> and <summary> tags. The second method uses JavaScript to toggle the visibility of the accordion content and the third method uses JavaScript to open one accordion at a time.

Method 1: Using HTML <details> and <summary> Tags to Build an Accordion

The simplest way is to use the HTML <details> and <summary> tags. It allows you to build an accordion without javascript. You can build a pure HTML accordion menu using the <details> and <summary> tags and a little bit of CSS or no CSS at all. Let's see how it works.

html
<details>
<summary>Header</summary>
<p>
Lorem ipsum, dolor sit amet consectetur adipiscing elit. Et neque, velit
quasi quos quia nulla omnis! Similique dolorum, veniam facilis aliquam est
fuga aperiam voluptatibus, sapiente atque vitae quia accusamus.
</p>
</details>

Pure HTML accordion menu using the details and summary tags

Pure HTML accordion menu using the `details` and `summary` tags

The <summary> tag contains the header, which summarizes what the accordion is all about. The <details> tag, on the other hand, includes the <summary> tag and the additional content of the accordion, as you can see from the code snippet above. So when you click on the header(i.e., summary), the details drop to reveal the additional content.

You can also add CSS to style the accordion. Let's see how that works.

css
/* accordion card */
details {
width: 280px;
border: double goldenrod;
background-color: white;
}
/* accordion title */
summary {
font-weight: bold;
color: #202020;
position: relative;
padding: 10px;
margin-bottom: 0;
}
/* accordion content */
p {
border-top: solid 1px goldenrod;
padding: 10px;
color: #3d3b3b;
}

A simple accordion menu using HTML `details` and `summary` tags with CSS styling

A simple accordion menu using HTML `details` and `summary` tags with CSS styling

Method 2: Using HTML, CSS, and JavaScript to Build an Accordion

We'll build an accordion using Javascript, HTML and CSS in this method. With Javascript, when a user clicks on a header, the accordion will toggle the visibility of the corresponding content.

html
<div class="accordion-card">
<h3 class="accordion-card__header">
Header
<span class="icon"> + </span>
</h3>
<p class="accordion-card__content">
Lorem ipsum, dolor sit amet consectetur adipiscing elit. Et neque, velit
quasi quos quia nulla omnis! Similique dolorum, veniam facilis aliquam est
fuga aperiam voluptatibus, sapiente atque vitae quia accusamus.
</p>
</div>

Here we have a <div> tag that contains an <h3> tag for the header and a <p> tag for the content. We also have an icon inside the header that will rotate at a 45deg angle, with its color changing to red when the accordion is open and the styles reverting when it is closed.

Let's add the CSS.

css
/* accordion card */
.accordion-card {
width: 280px;
border: double goldenrod;
background-color: white;
}
/* accordion header */
.accordion-card__header {
color: #202020;
position: relative;
padding: 10px;
margin: 0;
}
/* icon */
.icon {
position: absolute;
right: 10px;
color: goldenrod;
transform: rotate(0deg);
transition: transform 300ms, color 300ms;
}
/* accordion content */
.accordion-card__content {
border-top: solid 1px goldenrod;
padding: 10px;
color: #3d3b3b;
display: none;
margin: 0;
}
/* javascript css classes to be added and removed */
.toggleIcon {
transform: rotate(45deg);
color: hsl(0, 70%, 50%);
}
.active {
display: block;
}
Verpex hostingVerpex hosting

Let's add the JavaScript.

js
// variables
const accordionBtnToggle = document.querySelectorAll(".accordion-card__header");

From the function above, all the headers are selected using querySelectorAll, and saved in an array named accordionBtnToggle.

js
// Adding event listener to the accordion toggle button
for (i of accordionBtnToggle) {
i.addEventListener("click", accordionToggleFunction);
}

An event listener is added to all the headers so that when the user clicks on any of the headers, a function called accordionToggleFunction is run. Let's create that function.

js
// function to open an accordion
function accordionToggleFunction() {
this.nextElementSibling.classList.toggle("active");
this.children[0].classList.toggle("toggleIcon");
}

This function runs when a user clicks on a particular header. The content, which is its next element sibling (since both of them are stored in the same <div> element), will have an active class attached to it, which then makes the content's style go from a display of none to a display of block.

The children[0], on the other hand, select the icon (which is the first child of the <h3> tag, i.e., the header) and adds a class of toggleIcon to it, which changes the degree angle and color of the icon on click.

Accordion menu using Html, CSS and JavaScript

Accordion menu using Html, CSS, and JavaScript

Now, let's move on to our third example.

Method 3: Accordion Menu Using JavaScript to Open One Accordion at a Time

This third example is the same as our second example. The only difference is that when a user clicks on the header of a particular accordion, if the content of another header is currently open, it will automatically be closed before showing the content of the header you clicked on. Basically, it's an accordion menu that closes opened accordions when you click on one. The html and CSS code remains the same, but in our JavaScript code, the function that runs is different.

js
// function to open an accordion while closing the others
function accordionToggleFunction() {
for (i of accordionBtnToggle) {
i.nextElementSibling.style.display = "none";
i.children[0].classList.remove("toggleIcon");
}
if (this.nextElementSibling.style.display == "none") {
this.nextElementSibling.style.display = "block";
this.children[0].classList.add("toggleIcon");
}
}

From the code above, when the user clicks on a particular header, the for…of loop first of all loops through the content of each accordion, giving them a style of display none and then loops through all the icons, also removing the toggleIcon class from all of them.

The if statement then checks to see if the corresponding content of the particular header clicked on has a display style of none. If it does, it then adds a style of display block to it and the toggleIcon class name to its icon.

When the user clicks on another header, the for…of loop runs again, setting the display of all the content to none and removing the toggleIcon class from the icons, including the ones we just added to the previous content and icon. The if statement then runs again and adds the active and toggleIcon classes to the content and icon of the new header we just clicked on.

JavaScript accordion menu that closes opened accordions when you click on one

JavaScript accordion menu that closes opened accordions when you click on one

Now that you have seen three simple ways to build an accordion, I hope you will use one in your next project. What JavaScript project would you like me to do next? Let me know on X (Twitter).

Till next time, guys, Byeee!

man smiling and waving goodbye

Image from

giphy.com

Enjoying this article?

Be the first to read new content, and more!

Occasional emails. No spam. Unsubscribe anytime.

Resources

Connect With Me

Follow me on X(Twitter), and LinkedIn to stay updated with my latest content.

If you like my notes and want to support me, you can sponsor me on GitHub Sponsor, or you can buy me a virtual ice cream on ByMeACoffee or Selar. I would really appreciate it. 🙏

For other ways to support me, visit my Sponsorship page or Affiliate Links page.

Frequently Asked Questions

1. What is an Accordion Menu?

An accordion menu, often called an "accordion," is a user interface component commonly used to display content in a compact and organized manner. It consists of a list of headers, which can be expanded or collapsed to reveal or hide additional content associated with that particular header. Accordions are particularly useful for web pages that aim to present a substantial amount of information without overwhelming the user with too much content at once.

2. How do I build an Accordion?

There are several ways to build an accordion. In this article, we explored three simple ways to do so. The first method uses the HTML details and summary tags. The second and third methods use JavaScript to toggle the visibility of the accordion content.

3. Can you build an accordion without JavaScript?

Yes, you can build an accordion without JavaScript. The simplest way is to use the HTML details and summary tags.

4. What Are the Benefits of Using Accordions on a Website?

Accordions offer several benefits, including saving space on web pages, providing a clean and organized way to present content, reducing clutter, and enhancing user experience by allowing users to focus on the content they're interested in.

5. Are There Any SEO Considerations When Using Accordions?

Yes, there are SEO considerations when using accordions. Search engines can index hidden content within accordions, but ensuring it is relevant and valuable is important. Properly structured HTML and informative summary labels can also help search engines understand the content.

6. How Can I Style Accordions to Match My Website's Design?

Styling accordions can be done through CSS to match your website's design. You can modify the fonts, colors, borders, and animations to achieve the desired look. Adding CSS classes to different accordion components allows for precise styling.

7. What Are the Best Practices for Accessible Accordions?

Building accessible accordions is important for all users. Use semantic HTML elements like button for headers and p for content, provide keyboard navigation, and ensure screen readers can interpret the content. ARIA attributes, such as aria-expanded and aria-controls, can be used to enhance accessibility.

8. Can I Have Nested Accordions?

Yes, it's possible to have nested accordions. Nested accordions allow you to organize content hierarchically. Each nested level functions independently, and clicking on a header within a nested accordion reveals or hides content within that section.

9. What Are Common Use Cases for Accordions on Websites?

Accordions are commonly used for Frequently Asked Questions (FAQ) sections, product descriptions, long content that needs organization, and any scenario where you want to present information in a compact and user-friendly way.

10. Are There JavaScript Libraries for Building Accordions?

Yes, JavaScript libraries and frameworks, such as Bootstrap and react-accessible-accordion, provide pre-built accordion components. These libraries can simplify the process of creating accordions with additional features and customization options.

11. What is the FAQ accordion?

A FAQ accordion, short for Frequently Asked Questions accordion, is a user interface element commonly used on websites to display a list of frequently asked questions and their corresponding answers in an organized and space-efficient manner. It allows users to easily access specific information by clicking on a question, which then reveals the corresponding answer.

Subscribe to my newsletter 💌

Stay in the loop on the latest articles, tutorials, projects, and exclusive content focused on web development! 💻📚✨