How to Build Accordion Menu using JavaScript ? Last Updated : 23 Jul, 2024 Comments Improve Suggest changes Like Article Like 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:Dynamic Accordion Sample ImagePrerequisites:HTMLCSSJavaScriptApproach: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:Project StructureExample: This example describes the basic implementation for creating the accordion menu using JavaScript. 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( "https://fonts.googleapis.com/css2?family=Poppins:wght@300&display=swap"); /* 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); } 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); } Output: Comment More infoAdvertise with us Next Article How to Build Accordion Menu using JavaScript ? J jatinsharmatu54 Follow Improve Article Tags : JavaScript Web Technologies JavaScript-Questions Similar Reads JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav 11 min read Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De 5 min read React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications 15+ min read JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as 15+ min read React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon 8 min read Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w 8 min read NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net 15+ min read HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML 14 min read What is an API (Application Programming Interface) In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms.What is an API?An API is a set of 10 min read Introduction of Firewall in Computer Network A firewall is a network security device either hardware or software-based which monitors all incoming and outgoing traffic and based on a defined set of security rules it accepts, rejects, or drops that specific traffic. It acts like a security guard that helps keep your digital world safe from unwa 10 min read Like