Skip to main content

Development

Implementing an Accordion with JavaScript: A Simple Guide

Closeup Of Program Developer Writing Software On Multiple Computer Screens At Home Office

An accordion is a UI element that displays content in a compact, space-saving way. It lets users expand or collapse sections, making it a great choice for FAQ sections, menus, or any content that can be organized into collapsible panels.

In this guide, we’ll walk you through how to implement a simple accordion with HTML, CSS, and JavaScript.

 

What is an Accordion?

An accordion typically consists of multiple sections. Each section has a title and hidden content that is revealed when the title is clicked. Clicking one section title hides others while revealing the clicked one. This creates a clean and interactive user experience.

Preview:

Accordion

Step 1: Index.html (Our HTML Structure)

Let’s start with the basic HTML structure of the accordion.

Here’s the code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="index.css" rel="stylesheet">
  <title>Welcome in my accordion</title>
</head>
<body>

  <div class="accordion">
    <h1><i>Generals Questions</i></h1>
    <div class="expand">
      <button type="button" class="btn_expand">
      </button>
    </div>
    <div class="accordion-item hide">
      <h3 class="title"> You Accept Major Credit Cards?</h3>
      <div class="content">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
          dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
          commodo consequat.</p>
      </div>
    </div>
    <div class="accordion-item hide">
      <h3 class="title"> Do You Support Local Farmers ? </h3>
      <div class="content">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
          dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
          commodo consequat.</p>
      </div>
    </div>
    <div class="accordion-item hide">
      <h3 class="title"> Do You Use Organic Ingrediants ? </h3>
      <div class="content">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
          dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
          commodo consequat.</p>
      </div>
    </div>

  </div>
<script src="index.js"></script>
</body>
</html>

Key Elements of the HTML

    • Accordion Container: The main wrapper for the accordion, which holds all the items.
    • Accordion Items: Each item consists of a title (<h3>) and content (<div class=”content”>), which is initially hidden.
    • Expand All Button: This button allows users to either expand or collapse all sections at once.

 

Step 2: index.css (Styling the Page with CSS)

While we won’t go into full detail about the CSS here, it’s crucial for making the accordion look presentable. The .hide class is used to hide content by default, while the .show class is used to display content when the accordion section is expanded.

.accordion-item .content {
  display: none;
}
.accordion-item.show .content {
  display: block;
}
.accordion-item.hide .content {
  display: none;
}

 

Step 3: JavaScript: Making It Interactive

Now, let’s dive into the JavaScript code that makes this accordion interactive. We’ll handle two key things:

  1. Toggling Individual Sections: When a user clicks on a section’s title, it should toggle between showing and hiding the content.
  2. Expanding/Collapsing All Sections: The “Expand All” button will let users expand or collapse all sections at once.

Here’s the code for that:

let content = document.querySelectorAll('.accordion-item');
let title = document.querySelectorAll('.accordion-item .title');
let x = 'isopen';
const clickDefault = () => {
    for (let i = 0; i < title.length; i++) {
        title[i].onclick = function () {
            let contentClass = this.parentNode.className;
            for (let j = 0; j < content.length; j++) {
                content[j].className = 'accordion-item hide';
            }
            if (contentClass == 'accordion-item hide') {
                this.parentNode.className = 'accordion-item show';
            }
        }
    }
}
clickDefault();
const clickExpand = () => {
    for (let i = 0; i < title.length; i++) {
        title[i].onclick = function () {
            let contentClass = this.parentNode.className;
            if (contentClass == 'accordion-item show') {
                this.parentNode.className = 'accordion-item hide';
            } else if (contentClass == 'accordion-item hide') {
                this.parentNode.className = 'accordion-item show';
                clickDefault();
            }
        }
    }
}
let expandButton = document.querySelector('.btn_expand');
expandButton.innerHTML = "Expand All";
expandButton.onclick = function () {
    if (x === 'isopen') {
        content.forEach((element = 'accordion-item hide') => {
            element.className = 'accordion-item show';
            expandButton.innerHTML = "Close All";
            x = 'isclose';
            clickExpand();
        });
    } else if (x === 'isclose') {
        content.forEach((element = 'accordion-item show') => {
            element.className = 'accordion-item hide';
            expandButton.innerHTML = "Expand All";
            x = 'isopen';
        });
    }
}

How the JavaScript Works:

  1. clickDefault Function:
    • This function listens for clicks on each title and toggles the visibility of the corresponding content. When a section is expanded, all others are collapsed.
  2. clickExpand Function:
    • This function allows each section to toggle between expanded and collapsed states independently when clicked.
  3. Handling the “Expand All” Button:
    • The expandButton.onclick function toggles between expanding and collapsing all sections. When clicked, the button changes text between “Expand All” and “Close All”.

Output:

When the Closed All button clicked all the sections will be closed:

Accordion

When the Expand All button clicked all the sections will be expanded:

Accordionexpand

When the “Expand All” button is clicked, all sections will be expanded, displaying all their content at once. Afterward, each item can be closed individually by clicking on its respective title, without automatically collapsing any other open sections.

Expandall Click Individual

When the “Close All” button is clicked, all the sections will be collapsed. Afterward, when you expand a new section, the previously opened section will automatically close, ensuring only one section is open at a time.

Accordion Individualclick

Conclusion

In this simple guide, we’ve built an accordion using HTML, CSS, and JavaScript. The accordion provides an efficient way to present large amounts of information in a compact form, enhancing user experience by allowing sections to expand or collapse with a simple click.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Sayyad Faizan Ali

Sayyad Faizan Ali is an associate technical consultant at Perficient with over three years of experience in Sitecore, including expertise in Sitecore SCORE and AEM CMS. He has worked on several Sitecore projects and specializes in front-end development with skills in HTML, SCSS, CSS, Bootstrap, JavaScript, jQuery, React, and Next.js.

More from this Author

Follow Us