3 Simple Ways to Build an Accordion

3 Simple Ways to Build an Accordion

Hi guys and welcome to my JavaScript Project Series. In this series, I will be building several JavaScript projects, from simple easy mini-projects to the little bit complex ones.

Before we start, I want you to know that all the codes to each project can be found on my GitHub account in a particular repo which will constantly be updated as I publish more notes on different projects. I have also deployed a live link where you can view and interact with the finished projects.

Prerequisites

I am going to assume that you are already familiar with using Html, CSS, and JavaScript and also have a basic understanding of how JavaScript DOM Manipulation works.

Now let's get started with our first project; 3 Simple Ways to Build an Accordion.

First of all, What is an Accordion Menu?

An accordion menu is one that contains a vertical list of headers that when selected or opened hides or reveals additional content relating to the header. Oftentimes, they can be found on FAQ pages, where users can easily scan the list of questions without getting distracted by the answers, giving them control to click and view the answers to the questions that interest them.

Now let's build our accordions.

How to Build an Accordion

As the title of this note denotes, I am going to show you 3 simple and different ways to build an accordion.

Accordion Example 1

This first example is the simplest and easiest to build and it doesn't involve you writing any JavaScript code. You just have to use two html tags called summary and details.

<details class="accordion1-card">
  <summary class="accordion1-card__header">Header</summary>
  <p class="accordion1-card__body">
        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>

The summary tag contains the header which gives you a summary of what the accordion is all about. The details tag on the other hand contains the summary tag and the body or additional content of the accordion which can be placed in a p tag as you can see from the code snippet above. So when you click on the header(i.e. summary), the details dropdown to reveal the additional content.

Accordion 2 Example

In this second example, a few lines of JavaScript are involved. Here you would be listening for a click event on the header, so that when the user clicks on the header, a function is fired to toggle the display on the body or content.

Let's write our html,

<div class="accordion2-card">
 <h3 class="accordion2-card__header">
   Header
   <span class="icons material-icons-outlined">
     add_circle_outline
   </span>
 </h3>
 <p class="accordion2-card__body">
     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 element that contains an h3 tag for the header and a p tag for the body. We also have an icon inside the header which rotates at a 45deg angle with its color changing to red when the accordion is open, and the styles reverting back when the accordion is closed.

Let's add CSS to beautify it a little,

/* accordion card */
.accordion2-card {
  width: 280px;
  border: double goldenrod;
  background-color: white;
}

/* accordion header */
.accordion2-card__header {
  color: #202020;
  position: relative;
  padding: 10px;
  margin-bottom: 0;
}

/* icons */
.icons {
  position: absolute;
  right: 10px;
  color: goldenrod;
  transform: rotate(0deg);
  transition: transform 300ms, color 300ms;
}

/* accordion body */
.accordion2-card__body {
  border-top: solid 1px goldenrod;
  padding: 10px;
  color: #3d3b3b;
  display: none;
}

/* javascript css classes to be added and removed */
.toggleIcon {
  transform: rotate(45deg);
  color: hsl(0, 70%, 50%);
}

.active {
  display: block;
}

Time for the JavaScript.

//* Js code for accordion 2 example
// variables
const accordion2BtnToggle = document.querySelectorAll(
  ".accordion2-card__header"
);

Firstly, all the headers are selected using querySelectorAll and saving them as an array named accordion2BtnToggle.

// adding event listener to the accordion2 toggle button
for (i of accordion2BtnToggle) {
  i.addEventListener("click", accordion2ToggleFunction);
}

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

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

What this function does is that when the user clicks on a particular header, the body, 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 body’s style go from a display of none to a display of block.

The children[0] on the other hand, selects 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.

Now let's move on to our third example.

Accordion 3 Example

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 here, if the body of another header is currently open, it will automatically be closed before showing the body of the header you clicked on. 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 accordion3ToggleFunction() {
  for (i of accordion3BtnToggle) {
    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 all the body 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 body of the particular header that was clicked on has a display style of none. If it does, it then adds a style of display block to it and adds our toggleIcon class to the icons.

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

Now that you have seen 3 simple ways to build an accordion, I hope that you will use this in your next project. What JavaScript project would you like me to build next? Till next time guys, Byeee!

bye(24).gif

Connect with Me 🔗

Follow me on Twitter, LinkedIn, and Instagram to stay updated with my latest content. If you like my notes and want to support me, you can buy me a coffee on ByMeACoffee or GetFidia. I love the taste of coffee. 😍 For other ways to support me, visit my Sponsorship Page or Partnership Page.

Resources