DEV Community

Cover image for How to Build an Accordion Menu 3 Simple Ways
Timonwa Akintokun
Timonwa Akintokun

Posted on • Originally published at timonwa.com on

How to Build an Accordion Menu 3 Simple Ways

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

via GIPHY

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 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

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.

<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>
Enter fullscreen mode Exit fullscreen mode

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 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.

/* 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;
}
Enter fullscreen mode Exit fullscreen mode

A simple accordion menu using HTML  raw `details` endraw  and  raw `summary` endraw  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.

<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>
Enter fullscreen mode Exit fullscreen mode

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.

/* 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;
}
Enter fullscreen mode Exit fullscreen mode

Let's add the JavaScript.

// variables
const accordionBtnToggle = document.querySelectorAll(".accordion-card__header");
Enter fullscreen mode Exit fullscreen mode

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

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

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.

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

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

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.

// 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");
  }
}
Enter fullscreen mode Exit fullscreen mode

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

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

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

via GIPHY

Useful Links

Connect With Me

Stay connected with me on Twitter and LinkedIn for the latest updates. You can support my work through GitHub Sponsor or BuyMeACoffee. For additional support options, check out my Sponsorship and Affiliate Links pages. Your support helps me create more valuable content!

Top comments (0)