Accordion

SECTION 1

This is the content of section 1.

SECTION 2

This is the content of section 2.

SECTION 3

This is the content of section 3.

HTML

                        <body>
    <div class="accordion">
        <div class="accordion-item">
            <div class="accordion-header">SECTION 1</div>
            <div class="accordion-content">
                <p>This is the content of section 1.</p>
            </div>
        </div>
        <div class="accordion-item">
            <div class="accordion-header">SECTION 2</div>
            <div class="accordion-content">
                <p>This is the content of section 2.</p>
            </div>
        </div>
        <div class="accordion-item">
            <div class="accordion-header">SECTION 3</div>
            <div class="accordion-content">
                <p>This is the content of section 3.</p>
            </div>
        </div>
    </div>
</body>

CSS

.accordion {
  width: 300px;
}

.accordion-item {
  margin-bottom: 5px;
}

.accordion-header {
  background-color: #000000;
  padding: 10px;
  cursor: pointer;
  font-weight: bold;
  color: white;
}

.accordion-content {
  /* display: block; */
  /* max-height: 1000px; */
  transition: max-height 0.6s ease;
  padding: 10px;
  overflow: hidden;
  background-color: #333333;
  color: white;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
  max-height: 0;
  display: none;
}

.accordion-content.active {
  display: block;
  max-height: 1000px;
}

  
JS

const accordionHeaders = document.querySelectorAll(".accordion-header");
const accordionContents = document.querySelectorAll(".accordion-content");

accordionHeaders.forEach((header) => {
  header.addEventListener("click", () => {
    const accordionItem = header.parentElement;
    const accordionContent = accordionItem.querySelector(".accordion-content");

    accordionContents.forEach((content) => {
      if (content !== accordionContent) {
        content.classList.remove("active");
        content.style.maxHeight = "0";
      }
    });

    accordionContent.classList.toggle("active");

    if (accordionContent.classList.contains("active")) {
      accordionContent.style.maxHeight = accordionContent.scrollHeight + "px";
    } else {
      accordionContent.style.maxHeight = "0";
    }
  });
});