How to Build an Accordion Menu 3 Simple Ways
Tags: javascript, tutorial, accordions, javascriptprojects
Published: 2022-04-01 09:34:47

---
title: How to Build an Accordion Menu 3 Simple Ways
published: true
description: Learn how to create HTML and JavaScript accordion menus for a cleaner and organized user experience in web design.
tags: javascript, tutorial, accordions, javascriptprojects
canonical_url: https://timonwa.com/blog/3-simple-ways-to-build-an-accordion
cover_image: https://res.cloudinary.com/denkuysrh/image/upload/v1691842411/Cover%20Images/Articles/3-simple-ways-to-build-an-accordion_zbfzzy.png
series: JavaScript Projects for Beginners
---

Welcome to this tutorial on building an accordion menu. Throughout this guide, we will explore three different methods to create accordions using HTML, CSS, and JavaScript.

Accordions are a great way to display content in a compact and organized manner, allowing users to selectively access information without distraction. Whether you are a beginner or looking to refine your skills, this tutorial will help you master the art of building accordions.

We will start this tutorial with a simple project: Accordions. 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](https://res.cloudinary.com/denkuysrh/image/upload/v1699723838/memes/gtL8MNgSES_u3xze8.gif)
<figcaption>via GIPHY</figcaption>

## 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](https://github.com/Timonwa/javascript-project-series). Additionally, explore the [live demo](https://javascript-project-series.vercel.app) 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 a 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](https://res.cloudinary.com/denkuysrh/image/upload/v1698058139/Article%20Images/Timonwa%27s%20Notes/3%20simple%20accordions/image1_sdv3cf.png)

<figcaption>A frequently asked questions accordion menu</figcaption>

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](https://res.cloudinary.com/denkuysrh/image/upload/v1698058454/Article%20Images/Timonwa%27s%20Notes/3%20simple%20accordions/image2_ntyttc.png)

<figcaption>
  Pure HTML accordion menu using the `details` and `summary` tags
</figcaption>

The `<summary>` tag contains the header, which summarizes what the accordion is about. The `<details>` tag includes the `<summary>` tag and the additional content of the accordion. 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](https://res.cloudinary.com/denkuysrh/image/upload/v1698058272/Article%20Images/Timonwa%27s%20Notes/3%20simple%20accordions/ezgif-1-bd0be6f987_zrauxx.gif)

<figcaption>
  A simple accordion menu using HTML `details` and `summary` tags with CSS
  styling
</figcaption>

### 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;
}
```

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](https://res.cloudinary.com/denkuysrh/image/upload/v1698059847/Article%20Images/Timonwa%27s%20Notes/3%20simple%20accordions/video2_krgaqm.gif)

<figcaption>Accordion menu using Html, CSS, and JavaScript</figcaption>

### 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 content to `none` and removing the `toggleIcon` class from all icons before running the if statement again.

![JavaScript accordion menu that closes opened accordions when you click on one](https://res.cloudinary.com/denkuysrh/image/upload/v1698061141/Article%20Images/Timonwa%27s%20Notes/3%20simple%20accordions/ezgif-1-e92ee6d226_sxh4tc.gif)

<figcaption>
  JavaScript accordion menu that closes opened accordions when you click on one
</figcaption>

## Conclusion

Accordions are a simple yet powerful way to display content in a compact and organized manner. By using HTML, CSS, and JavaScript, you can create dynamic and interactive accordion menus that enhance the user experience on your website. Practice these three methods and see which one suits your needs best.

If you found this tutorial helpful, please share it and check out my other articles for more coding tips and tricks.

Till next time, guys, Byeee!

![man smiling and waving goodbye](https://res.cloudinary.com/denkuysrh/image/upload/v1699723779/memes/HoDL1vbXj_in8iqi.gif)

<figcaption><a href="https://giphy.com/gifs/wave-hello-hi-I5bk7sUToEBxe">via GIPHY</a></figcaption>

## Useful Links

- [When Should You Use Accordions on Your Website](https://designtlc.com/when-should-you-use-accordions-on-your-website/)
- [JavaScript HTML DOM Navigation](https://www.w3schools.com/js/js_htmldom_navigation.asp)
- [Get the code on GitHub](https://github.com/Timonwa/javascript-project-series)
- [View the project](https://javascript-project-series.vercel.app/)
- [Interact with the code on Codepen](https://codepen.io/collection/zxoQZp)

## Connect With Me

Stay connected with me on [Twitter](https://twitter.com/Timonwa_) and [LinkedIn](https://www.linkedin.com/in/timonwa) for the latest updates. You can support my work through [GitHub Sponsor](https://github.com/sponsors/timonwa) or [BuyMeACoffee](https://www.buymeacoffee.com/timonwa). For additional support options, check out my [Sponsorship](https://timonwa.com/sponsorship) and [Affiliate Links](https://timonwa.com/affiliate-links) pages. Your support helps me create more valuable content!