Prevent first accordion from expanding on page load JS

Advertisements

I have a simple accordion developed using pure javascript no jQuery and Pure CSS also, and Everything working well, The issue is that the first accordion expanded when the page loaded, I tried many ways using CSS and JS But it not working, I’m bad in JavaScipt, I tried to remove active class on window load and it removed but it still expanded!! can you please help with this?

// ============== 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>

>Solution :

The below code will trigger clicking on the first header. Which will cause that accordion to expand. Just remove this code and it should stop auto expanding.

window.onload = function() {
  header[0].click();
}

Leave a ReplyCancel reply