JavaScript FAQ Accordion Code with Example

JavaScript FAQ Accordion
Code Snippet:FAQs accordion Javascript
Author: Deepak Saini
Published: January 19, 2024
Last Updated: January 22, 2024
Downloads: 1,323
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript accordion code snippet helps you to create an interactive FAQ section on a webpage. It allows users to smoothly expand and collapse individual FAQ items by clicking on them. This code uses JavaScript to toggle the visibility of the FAQs answers when the corresponding question is clicked. It’s helpful for organizing and presenting frequently asked questions in a user-friendly manner.

How to Create JavaScript FAQ Accordion

1. Create the HTML structure for the FAQ accordion as follows. Inside the <div class="accordion"> element, create individual FAQ items using the following code structure. Each FAQ item consists of a question and its corresponding answer. You can add more FAQ items as needed.

<h2>FAQ'S</h2>

<div class="accordion">
  <div class="accordion-item">
    <div class="accordion-item-header">
      What is Web Development?
    </div>
    <div class="accordion-item-body">
      <div class="accordion-item-body-content">
        Web Development broadly refers to the tasks associated with developing functional websites and applications for the Internet. The web development process includes web design, web content development, client-side/server-side scripting and network security configuration, among other tasks.
      </div>
    </div>
  </div>
  <div class="accordion-item">
    <div class="accordion-item-header">
      What is HTML?
    </div>
    <div class="accordion-item-body">
      <div class="accordion-item-body-content">
        HTML, aka HyperText Markup Language, is the dominant markup language for creating websites and anything that can be viewed in a web browser.
      </div>
    </div>
  </div>
  <div class="accordion-item">
    <div class="accordion-item-header">
      What are some basic technical skills of a Front-End developer?
    </div>
    <div class="accordion-item-body">
      <div class="accordion-item-body-content">
        <ul style="padding-left: 1rem;">
          <li>HTML, CSS, JavaScript</li>
          <li>Frameworks (CSS and JavaScript frameworks)</li>
          <li>Responsive Design</li>
          <li>Version Control/Git</li>
          <li>Testing/Debugging</li>
          <li>Browser Developer Tools</li>
          <li>Web Performance</li>
          <li>SEO (Search Engine Optimization)</li>
          <!-- <li>CSS Preprocessing</li> -->
          <li>Command Line</li>
          <li>CMS (Content Management System)</li>
        </ul>
      </div>
    </div>
  </div>
  <div class="accordion-item">
    <div class="accordion-item-header">
      What is HTTP?
    </div>
    <div class="accordion-item-body">
      <div class="accordion-item-body-content">
        HTTP, aka HyperText Transfer Protocol, is the underlying protocol used by the World Wide Web and this protocol defines how messages are formatted and transmitted, and what actions Web servers and browsers should take in response to various commands.
      </div>
    </div>
  </div>
  <div class="accordion-item">
    <div class="accordion-item-header">
      What is CORS?
    </div>
    <div class="accordion-item-body">
      <div class="accordion-item-body-content">
        CORS, aka Cross-Origin Resource Sharing, is a mechanism that enables many resources (e.g. images, stylesheets, scripts, fonts) on a web page to be requested from another domain outside the domain from which the resource originated.
      </div>
    </div>
  </div>
</div>

2. Style your FAQ accordion by creating a “styles.css” file and defining the CSS styles for elements. You can customize colors, fonts, and other visual aspects to match your website’s design.

@import url("https://fonts.googleapis.com/css?family=Montserrat");

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: "Montserrat", sans-serif;
}
.accordion {
  width: 90%;
  max-width: 1000px;
  margin: 2rem auto;
}
.accordion-item {
  background-color: #fff;
  color: #111;
  margin: 1rem 0;
  border-radius: 0.5rem;
  box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.25);
}
.accordion-item-header {
  padding: 0.5rem 3rem 0.5rem 1rem;
  min-height: 3.5rem;
  line-height: 1.25rem;
  font-weight: bold;
  display: flex;
  align-items: center;
  position: relative;
  cursor: pointer;
}
.accordion-item-header::after {
  content: "+";
  font-size: 2rem;
  position: absolute;
  right: 1rem;
}
.accordion-item-header.active::after {
  content: "-";
}
.accordion-item-body {
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.2s ease-out;
}
.accordion-item-body-content {
  padding: 1rem;
  line-height: 1.5rem;
  border-top: 1px solid;
  border-image: linear-gradient(to right, transparent, #34495e, transparent) 1;
}

@media (max-width: 767px) {
  html {
    font-size: 14px;
  }
}

3. Create a “script.js” file and add the following JavaScript code. This code will make the FAQ items expand and collapse when the user clicks on the question headers.

const accordionItemHeaders = document.querySelectorAll(
  ".accordion-item-header"
);

accordionItemHeaders.forEach((accordionItemHeader) => {
  accordionItemHeader.addEventListener("click", (event) => {
    // Uncomment in case you only want to allow for the display of only one collapsed item at a time!

    const currentlyActiveAccordionItemHeader = document.querySelector(
      ".accordion-item-header.active"
    );
    if (
      currentlyActiveAccordionItemHeader &&
      currentlyActiveAccordionItemHeader !== accordionItemHeader
    ) {
      currentlyActiveAccordionItemHeader.classList.toggle("active");
      currentlyActiveAccordionItemHeader.nextElementSibling.style.maxHeight = 0;
    }
    accordionItemHeader.classList.toggle("active");
    const accordionItemBody = accordionItemHeader.nextElementSibling;
    if (accordionItemHeader.classList.contains("active")) {
      accordionItemBody.style.maxHeight = accordionItemBody.scrollHeight + "px";
    } else {
      accordionItemBody.style.maxHeight = 0;
    }
  });
});

Feel free to customize the FAQ items, styles, and add more questions and answers to fit your website’s needs. You can also integrate this accordion into an existing website by adapting the HTML and CSS to match your site’s design.

You’ve successfully created an FAQ accordion for your website using HTML, CSS, and JavaScript. Users can now easily find answers to their frequently asked questions in an interactive and user-friendly format. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

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

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X