Skip to main content

Accordion

Big O

Classic + open more than one​

document.addEventListener("DOMContentLoaded", function () {
const accordions = document.querySelectorAll<HTMLElement>(".accordion");
const multipleCheckbox = document.getElementById(
"multiselect",
) as HTMLInputElement;

accordions.forEach(function (accordion) {
const expandIcon = accordion.querySelector<HTMLElement>(".expand-icon");
const collapseIcon = accordion.querySelector<HTMLElement>(".collapse-icon");
const description = accordion.querySelector<HTMLElement>(".description");
const titleSection = accordion.querySelector<HTMLElement>(".title-section");

// Ensure elements exist before manipulating them
if (!expandIcon || !collapseIcon || !description || !titleSection) return;

// Collapse all sections initially
description.style.display = "none";
collapseIcon.style.display = "none";

// Expand the first accordion by default
if (accordion === accordions[0]) {
description.style.display = "block";
expandIcon.style.display = "none";
collapseIcon.style.display = "inline-block";
}

// Toggle accordion state function
function toggleAccordion() {
const isExpanded = description.style.display === "block";

if (!multipleCheckbox.checked) {
// Collapse all other accordions
accordions.forEach(function (otherAccordion) {
if (otherAccordion !== accordion) {
const otherDescription =
otherAccordion.querySelector<HTMLElement>(".description");
const otherExpandIcon =
otherAccordion.querySelector<HTMLElement>(".expand-icon");
const otherCollapseIcon =
otherAccordion.querySelector<HTMLElement>(".collapse-icon");

if (otherDescription && otherExpandIcon && otherCollapseIcon) {
otherDescription.style.display = "none";
otherExpandIcon.style.display = "inline-block";
otherCollapseIcon.style.display = "none";
}
}
});
}

// Toggle the current accordion
description.style.display = isExpanded ? "none" : "block";
expandIcon.style.display = isExpanded ? "inline-block" : "none";
collapseIcon.style.display = isExpanded ? "none" : "inline-block";
}

// Click event for expand icon
expandIcon.addEventListener("click", toggleAccordion);

// Click event for collapse icon
collapseIcon.addEventListener("click", toggleAccordion);

// Click event for the title section
titleSection.addEventListener("click", toggleAccordion);
});
});