How to Create an Accordion with HTML, CSS, and JavaScript

Introduction

An accordion is a collapsible content display pattern commonly used to hide and reveal sections of content. When one section is clicked, it expands, while the others collapse, making it easy to manage large amounts of content within limited space.

In this tutorial, you'll learn how to create a simple accordion using HTML, CSS, and JavaScript. We will implement interactivity to toggle the visibility of content panels when a section heading is clicked.

Development Steps

  1. Create the HTML Structure: Set up the basic structure for the accordion with headings and content.
  2. Style the Accordion Using CSS: Use CSS to style the accordion panels and their collapsed/expanded states.
  3. Add Interactivity with JavaScript: Use JavaScript to toggle the visibility of each section when clicked.
  4. Enhance the Accordion with Transitions: Add smooth transitions when panels open and close.

Step 1: Create the HTML Structure

We’ll begin by creating a simple HTML structure for the accordion. This will include button elements for the headers and div elements for the collapsible content.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Accordion Example</title>
</head>
<body>

    <!-- Step 1: Accordion HTML structure -->
    <div class="accordion">
        <button class="accordion-header">Section 1</button>
        <div class="accordion-content">
            <p>This is the content for section 1.</p>
        </div>

        <button class="accordion-header">Section 2</button>
        <div class="accordion-content">
            <p>This is the content for section 2.</p>
        </div>

        <button class="accordion-header">Section 3</button>
        <div class="accordion-content">
            <p>This is the content for section 3.</p>
        </div>
    </div>

</body>
</html>

Explanation:

  • accordion-header: Each section has a button that serves as the header, which the user can click to expand or collapse.
  • accordion-content: The content for each section is placed inside a div, and will be shown or hidden based on user interaction.

Step 2: Style the Accordion Using CSS

Next, we’ll add some basic styling for the accordion’s layout, including styles for the headers and hidden content.

/* Step 2: Basic styles for the accordion */
.accordion {
    width: 100%;
    max-width: 600px;
    margin: 0 auto;
    border: 1px solid #ccc;
    border-radius: 5px;
}

.accordion-header {
    background-color: #f1f1f1;
    color: #333;
    padding: 15px;
    cursor: pointer;
    border: none;
    outline: none;
    width: 100%;
    text-align: left;
    font-size: 18px;
    transition: background-color 0.3s ease;
}

.accordion-header:hover {
    background-color: #ddd;
}

.accordion-content {
    display: none;
    padding: 15px;
    border-top: 1px solid #ccc;
    background-color: #fff;
}

Explanation:

  • .accordion-header { padding: 15px; }: Adds padding and sets the text alignment for the headers.
  • .accordion-content { display: none; }: Initially hides the content of each section.
  • hover effect: Adds a background color change when the header is hovered over.

Step 3: Add Interactivity with JavaScript

We’ll now use JavaScript to toggle the visibility of each section when the corresponding header is clicked. We'll add an event listener to each header to control the collapse and expand actions.

<script>
    const headers = document.querySelectorAll('.accordion-header');

    headers.forEach(header => {
        header.addEventListener('click', () => {
            const content = header.nextElementSibling;

            // Toggle the display of the content
            if (content.style.display === 'block') {
                content.style.display = 'none';
            } else {
                content.style.display = 'block';
            }

            // Optionally, collapse other open sections
            headers.forEach(h => {
                const otherContent = h.nextElementSibling;
                if (otherContent !== content && otherContent.style.display === 'block') {
                    otherContent.style.display = 'none';
                }
            });
        });
    });
</script>

Explanation:

  • header.nextElementSibling: This selects the content div that immediately follows the clicked header.
  • content.style.display = 'block': Toggles between showing (block) and hiding (none) the content when the header is clicked.
  • Optionally close other sections: If you want only one section open at a time, we close other sections when a new one is opened.

Step 4: Enhance the Accordion with Transitions

To make the accordion feel smoother, we’ll add transitions that animate the opening and closing of the sections.

/* Step 4: Adding transitions for smooth collapse/expand */
.accordion-content {
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.3s ease;
}

.accordion-content.open {
    max-height: 200px;  /* Set to a large enough value */
}

Explanation:

  • max-height: 0;: Initially sets the height of the content to 0, hiding it.
  • .accordion-content.open { max-height: 200px; }: When the section is open, it expands to a maximum height of 200px. You can adjust the height or dynamically calculate it for larger content.

We also need to modify the JavaScript to toggle the open class instead of directly controlling the display property.

<script>
    headers.forEach(header => {
        header.addEventListener('click', () => {
            const content = header.nextElementSibling;

            // Toggle 'open' class for smooth transition
            content.classList.toggle('open');

            // Optionally, collapse other open sections
            headers.forEach(h => {
                const otherContent = h.nextElementSibling;
                if (otherContent !== content) {
                    otherContent.classList.remove('open');
                }
            });
        });
    });
</script>

Explanation:

  • classList.toggle('open'): Adds or removes the open class from the content, allowing the transition to work.
  • Closes other sections: This behavior ensures that only one section can be expanded at a time by removing the open class from other sections.

Complete Code

Here’s the complete code for a functional accordion:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Accordion Example</title>
    <style>
        /* Basic styles for the accordion */
        .accordion {
            width: 100%;
            max-width: 600px;
            margin: 20px auto;
            border: 1px solid #ccc;
            border-radius: 5px;
        }

        .accordion-header {
            background-color: #f1f1f1;
            color: #333;
            padding: 15px;
            cursor: pointer;
            border: none;
            outline: none;
            width: 100%;
            text-align: left;
            font-size: 18px;
            transition: background-color 0.3s ease;
        }

        .accordion-header:hover {
            background-color: #ddd;
        }

        .accordion-content {
            max-height: 0;
            overflow: hidden;
            transition: max-height 0.3s ease;
            padding: 0 15px;
            background-color: #fff;
        }

        .accordion-content.open {
            max-height: 200px;  /* Set to a large enough value */
            padding: 15px;
        }
    </style>
</head>
<body>

    <!-- Accordion HTML structure -->
    <div class="accordion">
        <button class="accordion-header">Section 1</button>
        <div class="accordion-content">
            <p>This is the content for section 1.</p>
        </div>

        <button class="accordion-header">Section 2</button>
        <div class="accordion-content">
            <p>This is the content for section 2.</p>
        </div>

        <button class="accordion-header">Section 3</button>
        <div class="accordion-content">
            <p>This is the content for section 3.</p>
        </div>
    </div>

    <!-- JavaScript for accordion functionality -->
    <script>
        const headers = document.querySelectorAll('.accordion-header');

        headers.forEach(header => {
            header.addEventListener('click', () => {
                const content = header.nextElementSibling;

                // Toggle 'open' class for smooth transition
                content.classList.toggle('open');

                // Optionally, collapse other open sections
                headers.forEach(h => {
                    const otherContent = h.nextElementSibling;
                    if (otherContent !== content) {
                        otherContent.classList.remove('open');
                   

 }
                });
            });
        });
    </script>

</body>
</html>

Output

You can play with the above HTML in Online HTML Editor and Compiler. Here is the output of the above HTML page.:

Conclusion

In this tutorial, you learned how to create an accordion using HTML, CSS, and JavaScript. By leveraging CSS transitions and JavaScript interactivity, you created a smooth, collapsible content area that expands and collapses when clicked. This type of UI element is great for improving user experience by neatly organizing large amounts of content.

Comments