Open In App

How to Build Accordion Menu using JavaScript ?

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:

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:



Project Structure:

Project Structure

Example: This example describes the basic implementation for creating the accordion menu using 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);
}




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




/* 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:



Gif Output for Dynamic Accordion


Article Tags :