I have a simple accordion created using only pure javascript
without jQuery and Pure CSS. Everything is functioning correctly, but the problem I am facing is that the first accordion is automatically expanded when the page loads. I have tried various methods using CSS
and JS
, but none of them seem to work. I am not very proficient in JavaScript, and I attempted to remove the active
class on window load, which did remove it, but the accordion still remains expanded. Can someone please assist me with this issue?
// ============== toggle accordion =================//
let header = document.querySelectorAll(".accordion-header");
// ============= get all accoridon header =============//
header.forEach(
(header) => {
header.addEventListener("click", function(e) {
let accordion = document.querySelectorAll(".accordion");
let parentElm = header.parentElement;
let siblings = this.nextElementSibling;
// ============= remove accordion body height ==========//
accordion.forEach((element) => {
element.children[1].style.maxHeight = null;
});
// =========== toggle active class ==============//
parentElm.classList.toggle("active");
if (parentElm.classList.contains("active")) {
// ============== remove active class from all the accordions ===//
accordion.forEach((element) => {
element.classList.remove("active");
});
// ============== toggle active class where we clicked ========//
parentElm.classList.toggle("active");
// ============= set max height ============//
if (siblings.style.maxHeight) {
siblings.style.maxHeight = null;
} else {
siblings.style.maxHeight = siblings.scrollHeight + "px";
}
}
});
}
);
window.onload = function() {
header[0].click();
}
.accordion-container {
padding: 0 100px;
}
.accordion .accordion-header {
padding: 15px 20px;
cursor: pointer;
position: relative;
}
.accordion .accordion-header h2 {
margin: 0;
font-size: 24px;
font-weight: 400;
line-height: 32px;
text-decoration: underline;
}
.accordion .accordion-body {
max-height: 0;
overflow: hidden;
transition: max-height ease 0.5s;
padding: 0 20px;
}
.accordion .accordion-body p {
font-weight: 400;
padding-bottom: 20px;
line-height: 1.5;
}
<div class="accordion">
<div class="accordion-header">
<h2>Accordion Header</h2>
</div>
<div class="accordion-body">
<p>Accordion Body</p>
</div>
</div>
<div class="accordion">
<div class="accordion-header">
<h2>Accordion Header</h2>
</div>
<div class="accordion-body">
<p>
<p>Accordion Body</p>
</p>
</div>
</div>