Building an Accordion Menu with JavaScript

An accordion menu is a graphical user interface element that allows the user to expand and collapse sections of content. It is commonly used to display a list of items with a limited amount of space, where only one item can be expanded at a time. In this article, we will look at how to build an accordion menu with JavaScript.

HTML Markup

The first step in building an accordion menu is to create the HTML markup. The structure of the menu should consist of a container element that holds the items, and each item should have a header and a content section. Here's an example of the HTML markup for an accordion menu:

php
Copy code
<div class="accordion">
  <div class="accordion-item">
    <div class="accordion-header">
      Item 1
    </div>
    <div class="accordion-content">
      Content for item 1
    </div>
  </div>
  <div class="accordion-item">
    <div class="accordion-header">
      Item 2
    </div>
    <div class="accordion-content">
      Content for item 2
    </div>
  </div>
  <div class="accordion-item">
    <div class="accordion-header">
      Item 3
    </div>
    <div class="accordion-content">
      Content for item 3
    </div>
  </div>
</div>
CSS Styles

Next, we will add some basic styles to the accordion menu. We will set the height of the content section to 0, so it is hidden by default. When the header is clicked, the content section will be expanded to show the content.

css
Copy code
.accordion-item {
  overflow: hidden;
}

.accordion-content {
  height: 0;
  transition: height 0.3s ease-out;
}

JavaScript

Now that we have the HTML and CSS in place, we can add the JavaScript to make the accordion menu work. The JavaScript will listen for clicks on the headers and toggle the visibility of the content sections.

javascript
Copy code
const accordionHeaders = document.querySelectorAll('.accordion-header');

accordionHeaders.forEach(header => {
  header.addEventListener('click', function() {
    const content = this.nextElementSibling;
    if (content.style.height === '0px') {
      content.style.height = content.scrollHeight + 'px';
    } else {
      content.style.height = '0px';
    }
  });
});

In this code, we first select all the headers using querySelectorAll and loop over them with forEach. For each header, we add a click event listener that toggles the height of the content section. If the content's height is 0, we set it to its scroll height, which is the height of the content when it is fully expanded. If the content's height is not 0, we set it back to 0.

Conclusion

In this article, we have looked at how to build an accordion menu with JavaScript. We started by creating the HTML markup, then added some basic styles, and finally added the JavaScript to make the accordion menu work.

Post a Comment

Previous Post Next Post