0
0
JavascriptHow-ToBeginner · 3 min read

How to Create Accordion in JavaScript: Simple Guide

To create an accordion in JavaScript, use clickable elements with event listeners that toggle the visibility of associated content panels by changing their CSS styles like display or max-height. This lets users expand or collapse sections by clicking headers.
📐

Syntax

An accordion typically consists of clickable headers and content panels. The JavaScript syntax involves selecting these elements and adding event listeners to toggle the content's visibility.

  • element.addEventListener('click', function): Attach a click event to toggle content.
  • element.style.display or element.classList.toggle(): Change visibility or styles.
javascript
const headers = document.querySelectorAll('.accordion-header');
headers.forEach(header => {
  header.addEventListener('click', () => {
    const panel = header.nextElementSibling;
    if (panel.style.display === 'block') {
      panel.style.display = 'none';
    } else {
      panel.style.display = 'block';
    }
  });
});
💻

Example

This example shows a simple accordion with three sections. Clicking a header toggles the visibility of its content panel.

html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Accordion</title>
<style>
  .accordion-header {
    background-color: #eee;
    cursor: pointer;
    padding: 10px;
    border: 1px solid #ccc;
    margin-top: 5px;
  }
  .accordion-content {
    display: none;
    padding: 10px;
    border: 1px solid #ccc;
    border-top: none;
  }
</style>
</head>
<body>

<div class="accordion-header">Section 1</div>
<div class="accordion-content">Content for section 1.</div>

<div class="accordion-header">Section 2</div>
<div class="accordion-content">Content for section 2.</div>

<div class="accordion-header">Section 3</div>
<div class="accordion-content">Content for section 3.</div>

<script>
const headers = document.querySelectorAll('.accordion-header');
headers.forEach(header => {
  header.addEventListener('click', () => {
    const panel = header.nextElementSibling;
    if (panel.style.display === 'block') {
      panel.style.display = 'none';
    } else {
      panel.style.display = 'block';
    }
  });
});
</script>

</body>
</html>
Output
When you open this HTML file in a browser, you see three headers labeled 'Section 1', 'Section 2', and 'Section 3'. Clicking any header shows or hides its content below it.
⚠️

Common Pitfalls

Common mistakes include:

  • Not selecting the correct content panel related to the clicked header.
  • Forgetting to initialize content panels as hidden in CSS.
  • Using style.display directly without considering existing CSS classes, which can cause conflicts.
  • Not handling multiple open sections if only one should be open at a time.
javascript
/* Wrong way: toggling all panels instead of the clicked one */
const headersWrong = document.querySelectorAll('.accordion-header');
headersWrong.forEach(header => {
  header.addEventListener('click', () => {
    const panels = document.querySelectorAll('.accordion-content');
    panels.forEach(panel => {
      panel.style.display = 'block'; // This opens all panels
    });
  });
});

/* Right way: toggle only the clicked panel */
const headersRight = document.querySelectorAll('.accordion-header');
headersRight.forEach(header => {
  header.addEventListener('click', () => {
    const panel = header.nextElementSibling;
    panel.style.display = panel.style.display === 'block' ? 'none' : 'block';
  });
});
📊

Quick Reference

  • Select headers: document.querySelectorAll('.accordion-header')
  • Attach click event: element.addEventListener('click', callback)
  • Toggle content: Change style.display between 'none' and 'block'
  • Initialize content hidden: Use CSS display: none;

Key Takeaways

Use event listeners on headers to toggle the visibility of their associated content panels.
Always initialize accordion content as hidden using CSS to avoid showing all content by default.
Toggle only the clicked section's content to avoid opening all sections at once.
Use simple CSS like display 'none' and 'block' for easy show/hide behavior.
Test your accordion in a browser to ensure clicking headers expands and collapses content correctly.