How to Create an Accordion in JavaScript?

In this article, we will show you how to create an interactive accordion element in JavaScript with this comprehensive guide.

We’ll start with the fundamentals and gradually move on to more advanced techniques, all aimed at elevating the user experience of your website.

So, let’s delve into the fascinating realm of JavaScript accordions and discover how to craft engaging and interactive UI elements.

What is accordion in JavaScript?

An accordion is usually composed of multiple collapsible panels, with each panel having a header that acts as a clickable trigger.

When users interact with the header a content section expands or collapses accordingly.

The HTML structure of an accordion typically involves nested elements, which can be styled using CSS and made interactive through the use of JavaScript.

Moreover, an accordion in JavaScript is a graphical control element that consists of a vertically stacked list of items, such as labels or thumbnails.

Each item can be “expanded” or “collapsed” to reveal the content associated with that item. It is a helpful way to organize and present information in a compact and user-friendly manner.

Accordions are commonly used in user interfaces to display frequently asked questions. If we click the question, it will reveal the answer.

How to Create an Accordion Menu Using HTML, CSS and JavaScript?

An accordion is a UI design pattern that allows you to show and hide content sections on a page. You can create an accordion using HTML, CSS, and JavaScript.

Here are the step-by-step guide to create an accordion:

Step 1: Create HTML structure

First, you need to create the HTML structure for the accordion.

It typically includes a button element for each section of the accordion and a corresponding content element that will be shown or hidden when the button is clicked.

Here’s an example:

<button class="accordion">Section 1</button>
<div class="panel">
  <p>Content for section 1...</p>
</div>

<button class="accordion">Section 2</button>
<div class="panel">
  <p>Content for section 2...</p>
</div>

<button class="accordion">Section 3</button>
<div class="panel">
  <p>Content for section 3...</p>
</div>

Here’s the complete example code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <link rel="stylesheet" href="style.css">
</head>
    <h1>How to Create an Accordion Menu Using HTML, CSS, and JavaScript?</h1>

<button class="accordion" >What is accordion in JavaScript?</button>
<div class="panel">

  <p>This is just a sample content for section 1...</p>
</div>

<button class="accordion">How to create a accordion in JavaScript? </button>
<div class="panel">
  <p>This is just a sample content for section 2...</p>
</div>

<button class="accordion"> How to use accordon in JavaScript?</button>
<div class="panel">
  <p>This is just a sample content for section 3...</p>
</div>

  <script src="script.js" type="text/javascript"></script>
</body>
</html>

Step 2: Add CSS

After creating the HTML structure, you need to add some CSS to style the accordion. It’s time to put your creative touch on the accordion’s appearance using CSS.

With CSS, you have the power to adjust the size, colors, transitions, and other visual elements of the accordion to achieve the desired look.

It includes styles for the button elements, as well as styles for the panel elements that will be shown or hidden.

It’s crucial to maintain consistency with your website’s theme and branding to create a harmonious design. So, make sure your accordion complements the overall aesthetics of your website.

Here’s an example:

/* Style the buttons */
.accordion {
  background-color: #eee;
  color: #0a0a0a;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  text-align: left;
  border: none;
  outline: none;
  transition: 0.4s;
}

/* Add a background color to the button when clicked */
.active, .accordion:hover {
  background-color: #ccc;
}

/* Style the panel */
.panel {
  padding: 0 18px;
  background-color: white;
  display: none; /* Hide the panel by default */
}

Step 3: Add JavaScript

Lastly, you need to add some JavaScript to make the accordion functional.

It includes adding an event listener to each button element that will toggle the display of the corresponding panel element when clicked.

Here’s an example:

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.display === "block") {
panel.style.display = "none";
} else {
panel.style.display = "block";
}
});
}

This is just one way to create an accordion using JavaScript. There are many other ways to achieve the same result, and you can customize the code to fit your specific needs.

Here’s the final output:

Conclusion

In conclusion, this article explores how to create interactive accordion elements in JavaScript through a comprehensive guide.

Accordions are a popular UI design pattern that allows users to show and hide content sections on a page, making it an effective way to organize and present information in a compact and user-friendly manner.

Keep in mind that this is just one approach to creating an accordion in JavaScript, and there are numerous ways to achieve similar results.

As you experiment and customize the code to suit your specific needs, you can craft engaging and interactive UI elements that enhance the user experience on your website.

We are hoping that this article provides you with enough information that help you understand on creating an accordion in JavaScript.

You can also check out the following article:

Thank you for reading itsourcecoders 😊.

Frequently Asked Questions

Is JavaScript still worth learning in 2026?
Yes. JavaScript runs on 98% of websites for the front-end, dominates the back-end via Node.js, powers mobile apps through React Native, builds desktop tools through Electron, and is the scripting layer for most AI tooling (LangChain.js, OpenAI SDK, Vercel AI). Whether you target web, mobile, AI, or full-stack capstones, JavaScript is the broadest single language you can learn.
What is the difference between var, let, and const?
var is function-scoped, hoisted to the top of its scope, and can be redeclared, which leads to bugs in modern code. let is block-scoped (only visible inside the nearest {}) and can be reassigned. const is block-scoped and cannot be reassigned, although object contents can still mutate. Default to const for everything, switch to let only when you actually need to reassign, and avoid var in any code written after 2017.
Which JavaScript version should I target in 2026?
Target ES2020 (ES11) as the safe baseline because every modern browser and Node.js 14+ supports it fully. ES2022 adds useful features like top-level await, private class fields with the # prefix, and the .at() array method. If you are writing for older browsers (IE11 or older Android WebViews), transpile down with Babel or use a build tool like Vite, esbuild, or webpack.
What is the best free editor for JavaScript?
Visual Studio Code is the industry standard, free, with built-in IntelliSense, debugger, terminal, Git, and a huge extension marketplace (ESLint, Prettier, GitHub Copilot, Tailwind). Install the JavaScript and TypeScript Nightly extension for the latest language features. JetBrains WebStorm is more powerful and free for students with a verified .edu email. For quick scratchpad work, the Chrome DevTools Sources panel includes a workspace and breakpoint debugger.
How do I run JavaScript locally vs in the browser?
In the browser: open DevTools with F12 (or right-click then Inspect), go to the Console tab, type or paste your code, press Enter. For HTML pages, add a script tag pointing to your .js file. Locally with Node.js: download Node from nodejs.org (LTS version), then run node script.js in your terminal from the file folder. Use the same Node setup for backend capstones, API integrations, and scripts that do not need a browser.
What can I build with JavaScript for my BSIT capstone?
Common BSIT capstones in JavaScript: full-stack web apps using React or Vue on the front-end with Node.js and Express on the back-end (MongoDB or MySQL for the database), real-time chat or notification systems using Socket.io, single-page dashboards with Chart.js or D3.js, cross-platform mobile apps with React Native, AI-powered chatbots using OpenAI SDK and LangChain.js, and Chrome extensions for productivity tools. Add Tailwind CSS for the UI and Vercel or Netlify for free deployment.
Caren Bautista

Technical Writer at PIES IT Solution

Responsible for crafting clear, well-structured, and beginner-friendly content across the platform. Handles the writing, proofreading, and editorial review of tutorials, guides, and documentation to ensure every article is accurate, readable, and easy to follow.

Expertise: Technical Writing · Content Creation · Documentation · Editorial Writing · JavaScript · TypeScript · Python · Python Errors · HTTP Errors · MS Excel  · View all posts by Caren Bautista →

Leave a Comment