Open In App

How to Build Accordion Menu using JavaScript ?

Last Updated : 25 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Accordion is used to render or hide, or toggle the view of the content with the help of adding the collapsible effect. It helps to manage and organize information in a compact and visually appealing manner. Accordion Menu may contain nested accordions, in order to render a large volume of content in an organized & systematic format. In this article, we will demonstrate how a dynamic accordion can be built using JavaScript. Here, the accordion will contain some titles and descriptions, along with the feature of adding more items to it. The accordion will finally look similar to the below image:

Screenshot-from-2023-07-06-14-08-43

Dynamic Accordion Sample Image

Prerequisites:

Approach:

The below approach will be utilized to create the accordion menu with the dynamic feature to include it in the accordion:

  • Create the <div> that has the accordion class that will contain different input fields and button tags defined with class names and IDs.
  • Add the different styling properties to the accordion using classes and elements that will define the padding, margin, font sizes to text, alignments, colors, etc to the specific elements.
  • In JavaScript, define 2 arrays that will contain the title & description details, & declare the loadItems() method to render the initial items in the array/ list using JavaScript array.map() method.
  • The addItem() method is defined for adding the new custom topics and their description input by the user with the input validation.
  • Now, create the createItem() method that is utilized to declare for creating each component whether custom or predefined items with the help of the createElement(), classlist() & appendChild() methods, in order to insert it into the Html DOM. Here, the user simply needs to click on individual topics to expand the description part and also can set more custom topics in the accordion.

Project Structure:

Screenshot-from-2023-07-06-12-54-03

Project Structure

Example: This example describes the basic implementation for creating the accordion menu using JavaScript.

Javascript




// script.js
  
// Creating list of title and description
const accordionTitles = [
    "What is HTML?",
    "What is CSS?",
    "What is JavaScript?",
];
const accordionDesc = [
  
    `HTML stands for HyperText Markup Language.
    It is used to design web pages using a markup language.`,
  
    `Cascading Style Sheets, fondly referred to as 
    CSS, is a simply designed language intended to
    simplify the process of making web pages presentable.`,
  
    `JavaScript is a lightweight, cross-platform,
    single-threaded, and interpreted compiled
    programming language which is also known
    as the scripting language for webpages`,
];
  
// To load items in start
function loadItem() {
    accordionTitles.map((e, i) => {
        createItem(e, accordionDesc[i]);
    });
}
loadItem();
  
// Funcion to add new items
function addItem() {
    // Getting value from input
    const title = document.getElementById("title").value;
    const des =
        document.getElementById("description").value;
  
    // Validating input values
    if (!title || !des) {
        window.alert("Incomplete input");
    } else {
        createItem(title, des);
    }
}
  
// Function to show items in accordion
function createItem(title, desc) {
  
    // Creating new item in accordion
    // Creating title component
    const head = document.createElement("div");
    head.classList.add("accordion-header");
    head.innerText = title;
  
    // Creting description component
    const des = document.createElement("div");
    des.classList.add("accordion-content");
  
    const p = document.createElement("p");
    p.innerText = desc;
    des.appendChild(p);
  
    const item = document.createElement("div");
    head.classList.add("accordion-item");
  
    // To hide or show descripton on click
    head.addEventListener("click", () => {
        des.classList.toggle("active");
        if (des.style.display === "block") {
            des.style.display = "none";
        } else {
            des.style.display = "block";
        }
    });
  
    // Combine title and desc into new item
    item.appendChild(head);
    item.appendChild(des);
    document.getElementById("menu").appendChild(item);
}


HTML




<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
  
<head>
    <title></title>
    <meta charset="UTF-8" />
    <meta name="viewport" 
          content="width=device-width, 
                   initial-scale=1" />
    <link href="style.css" 
          rel="stylesheet" />
    <script src="script.js"></script>
</head>
  
<body>
    <!-- Card container for project -->
    <div class="card">
        
        <!-- Heading or title -->
        <h2>Dynamic Accordion using JavaScript</h2>
  
        <!-- container for accordion items -->
        <div class="accordion" 
             id="menu"></div>
  
        <!-- Input for new item -->
        <div class="add">
            <h3>Add Custom</h3>
            <input type="text" 
                   id="title" 
                   placeholder="Title" />
            <input type="text" 
                   id="description"
                   placeholder="Description" />
            <button type="submit" 
                    onclick="addItem()">
                Add Item
            </button>
        </div>
    </div>
</body>
  
</html>


CSS




/* style.css */
  
/* Importing font family */
@import url(
  
/* Styling universal selector */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
  
/* Style body element */
body {
    min-height: 50vh;
    display: flex;
    align-items: center;
    text-align: center;
    justify-content: center;
    background: hsl(137, 100%, 86%);
    font-family: "Poppins", sans-serif;
}
  
/* Styling card container */
.card {
    max-width: 33rem;
    background: #fff;
    margin: 0 1rem;
    padding: 1rem;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
    width: 100%;
    border-radius: 0.5rem;
}
  
/* style accordion */
.accordion {
    margin: 5%;
    text-align: left;
}
  
/* style for accordion items */
.accordion-item {
    border-bottom: 1px solid #ddd;
    font-size: larger;
}
  
/* Style for accordion head/title */
.accordion-header {
    background-color: #f5f5f5;
    padding: 10px;
    cursor: pointer;
}
  
/* Accordion item description */
.accordion-content {
    padding: 10px;
    display: none;
}
  
/* Input box and button */
.add {
    padding: auto;
}
  
#title {
    width: 4vw;
    font-size: larger;
}
  
#description {
    font-size: large;
    width: 14vw;
}
  
button {
    border-radius: 5px;
    padding: 5px;
    font-size: large;
    color: #dbeefa;
    background-color: rgb(151, 161, 133);
}


Output:

Peek-2023-07-06-14-15

Gif Output for Dynamic Accordion



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads