Open In App

Accordion using JavaScript

Last Updated : 20 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Accordion in HTML is commonly used to refer to a user interface (UI) component that allows you to show or hide content sections with a collapsible effect. It is used to manage and organize information in a compact and visually appealing manner. In this tutorial, we are going to build an accordion using HTML, CSS, and JavaScript.

Functionalities we want in an Accordion:

  • Initially, only questions will be displayed and a line separates each question.
  • On clicking the question or plus icon, the answer will be displayed.
  • Once the answer section is displayed, the plus icon will be replaced by the minus icon.
  • When we click on another question, the previously displayed answer will be hidden.

Here is the sample image of the accordion we are going to make.
 

Screenshot-2023-05-30-095544.png

Accordion Sample Image

To start making Accordion using javascript we need three files index.html, style.css, and script.js. Each file code is given below you can directly paste it into your respective files. But before directly going to the code we need a font awesome icon for the plus and minus icons. To get this we need font awesome CDN link which is given below.

Font Awesome CDN(include in HTML file):

https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css

Project Structure:

Accordion (Folder Name)
- index.html
- style.css
- script.js

Example: In the below example code we will implement the above-discussed functionalities.

  • HTML Code: It is used to describe the structure of the accordion, we have used a parent div, and inside that we have taken 3 div’s each for one question.
  • CSS Code: After writing the HTML Code, we will start the styling part of the accordion and 2 icons ‘+’ and ‘-‘ to show and hide the answers.
  • JavaScript Code: We will use forEach loop to loop all the questions and add EventListener whenever the user clicks on the question. If the user clicks then we will toggle the is-open class. Will do the same for hiding the content.

Javascript




const accordionContent = document.querySelectorAll(".accordion-content");
  
accordionContent.forEach((item,index)=>{
    let header = item.querySelector("header");
    header.addEventListener("click", ()=>{
        item.classList.toggle("is-open");
  
        let description = item.querySelector(".accordion-content-description");
        if(item.classList.contains("is-open")){
            // Scrollheight property return the height of
            // an element including padding
            description.style.height=`${description.scrollHeight}px`; 
            item.querySelector("i").classList.replace("fa-plus","fa-minus");
        }else{
            description.style.height = "0px";
            item.querySelector("i").classList.replace("fa-minus","fa-plus");
        }
        // function to pass the index number of clicked header
        removeOpenedContent(index); 
    })
})
  
function removeOpenedContent(index){
    accordionContent.forEach((item2,index2)=>{
        if(index != index2){
            item2.classList.remove("is-open");
            let descrip = item2.querySelector(".accordion-content-description");
            descrip.style.height="0px";
            item2.querySelector("i").classList.replace("fa-minus","fa-plus");
        }
    })
}


HTML




<!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">
    <!-- css -->
    <link rel="stylesheet" href="style.css">
    <!-- Fontawesome CDN link  -->
    <link rel="stylesheet" 
          href=
  
    <title>Accordion using javascript</title>
</head>
<body>
    <div class="accordion">
        <h2>Accordion Using JavaScript</h2>
        <div class="accordion-content">
            <header>
                <span class="accordion-content-title">
                      What is GeeksforGeeks?
                  </span>
                <i class="fa-solid fa-plus"></i>
            </header>
            <p class="accordion-content-description">
                  GeeksforGeeks is a one stop solution 
                  for all computer science students.
            </p>
        </div>
        <div class="accordion-content">
            <header>
                <span class="accordion-content-title">
                      Which is the best portal to study Computer Science?
                  </span>
                <i class="fa-solid fa-plus"></i>
            </header>
            <p class="accordion-content-description"
                  GeeksforGeeks is the best Computer Science portal 
                  for geeks. It contains well written, well thought 
                  and well explained computer science and programming articles.
            </p>
        </div>
        <div class="accordion-content">
            <header>
                <span class="accordion-content-title">
                      What GeeksforGeeks offer us?
                  </span>
                <i class="fa-solid fa-plus"></i>
            </header>
            <p class="accordion-content-description"
                  GeeksforGeeks offers Free Tutorials, 
                  Millions of Articles, Live, Online and 
                  Classroom Courses,Frequent Coding Competitions, 
                  Webinars by Industry Experts, Internship opportunities 
                  and Job Opportunities.
            </p>
        </div>
    </div>
   <script src="script.js"></script>
</body>
</html>


CSS




*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
     
}
body{
    min-height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #dbeefa;
    font-family: 'Poppins', sans-serif;
}
.accordion{
    max-width: 33rem;
    width: 100%;
    background: #FFF;
    margin:0 1rem;
    padding: 1rem;
    border-radius: 0.5rem;
    box-shadow: 0 0 5px rgba(0,0,0,0.2);
}
.accordion .accordion-content{
    margin:10px 0;
    border-radius: 5px;
    background-color: #e8ffdc;
    border-color: #bbffaa;
    overflow: hidden;
}
  
.accordion-content.is-open{
    padding-bottom: 10px;
}
.accordion-content header{
    display:flex;
    min-height: 50px;
    padding: 0 15px;
    cursor: pointer;
    align-items: center;
    justify-content: space-between;
    transition:all 0.2s linear;
}
.accordion-content.is-open header{
    min-height: 35px;
}
.accordion-content-title{
    font-size: 1rem;
    font-weight: 600;
    color:#000000;
}
.accordion-content-description{
    height:0;
    font-size: 13px;
    color:#000000;
    font-weight: 400;
    padding: 0 15px;
}


Output: Click here to see live code output

AccordionGif.gif

Accordion using JavaScript



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads