Stop the initial expansion of the first accordion with JavaScript on page load

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>

Answer №1

This snippet of code will automatically simulate a click on the primary header, resulting in the expansion of the accordion. Simply deleting this code will prevent the auto-expansion from occurring.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Change UL to a JSON format

I am attempting to transform an entire unordered list (UL) and its child elements into a JSON object. Here is the approach we took: function extractData(element) { element.find('li').each(function () { data.push({ "name": $(this).fi ...

Experience the full power of the bootstrap grid system with a unique feature: nested overflow-y scrolling

Struggling with the bootstrap grid and a nested div with overflow-y. I followed advice from this stack overflow post, attempting to add min-height:0 to the parent ancestor, but can't seem to make it work. View screenshot here - Chrome on the left, Fi ...

In Vue, you can dynamically load a JavaScript file containing a JavaScript object during runtime

I'm in the process of developing a no-code application with Vue. I have come across an issue where I cannot add functions to a JSON file that I want to import at runtime. As a workaround, I decided to use a JavaScript or TypeScript file to store the J ...

Tips for posting images upon clicking a div instead of a submit button

I previously had a code that allowed users to click on the submit button and have the text inside a contenteditable div passed to upload.php using JQuery, inserted into a database, and immediately displayed. Now, I want to modify this code to also handle i ...

Continue extending the footer as the screen size decreases

Could anyone offer some assistance? I'm currently working on a project and facing issues with getting the footer to always be pushed down as the screen size decreases. As of now, my content is going under the footer instead. Any help would be greatly ...

Creating a concise TypeScript declaration file for an established JavaScript library

I'm interested in utilizing the neat-csv library, however, I have encountered an issue with it not having a typescript definition file available. Various blogs suggest creating a basic definition file as a starting point: declare var neatCsv: any; M ...

Preserving State in React Router Through Page Reload

I recently set up a react router in order to display my Navbar on all routes except the login page. To achieve this, I created a Layout component that ensures users are redirected back to the Login page if they are not authenticated. Currently, I'm st ...

FingerprintJS is experiencing an issue with the navigator object not being defined, resulting in

I am currently working on extracting browser fingerprint using fingerprintjs2, an npm package in Javascript. However, I encountered the following error: ReferenceError: navigator is not defined Error Logs: https://i.sstatic.net/lWL9Y.png Code Snippet: ...

Is there an XML File Wrapper to Generate PDF Output?

Greetings Forum Members, I have been given the responsibility of creating a PDF file from multiple XML files. Has anyone come across an XML wrapper file before? This type of file would essentially contain a list of all the source XML file names in a spec ...

Can a CSS hover effect transition modify the color scheme?

I have multiple buttons on a single page, and I want the hover effect to be applied to all of them with just one code using jQuery. Please review my code below. $(document).ready(function(){ $('.button').hover(function(){ var bc=$(this ...

Monitor modifications to the form as the user navigates away from the page or refreshes

Currently, I am working on a form that was created using Formik and React Hooks. I would greatly appreciate any suggestions on how to track changes made to the form when a user clicks the home button or refreshes/reloads the page. I attempted to use the b ...

Sending a JWT token to a middleware with a GET request in Express Node.js - the proper way

Struggling with Js and web development, I've scoured the web for a solution to no avail... After completing a project for a small lab, my current challenge is creating a login page and generating a web token using JWT... I successfully created a use ...

Creating a Dynamic Form with jQuery, AJAX, PHP, and MySQL for Multiple Input Fields

Success! The code is now functional. <form name="registration" id="registration" action="" method="post"> <div id="reg_names"> <div class="control-group"> <label>Name</label> <div class= ...

html Comparison of Documents

My goal is to compare HTML documents to see if they have the same tags in the same arrangement, regardless of different inner text and attribute values. I am only interested in comparing the general tag structure, such as: <html> <head> </h ...

Tips for utilizing a function to assess ngClass conditional statement in Angular 2

So as I loop through my list using *ngFor, the code snippet is like this: [ngClass]="{'first':isStartDate(event,day)}" The function isStartDate is defined in my component. An error message appeared: "Unexpected token : " ...

The issue of JQuery UI Dialog remaining open even after triggering it through an Input focus event

I am facing an issue with JQuery and JQuery UI. I thought upgrading to the latest stable version would solve it, but unfortunately, that was not the case. I am currently using Chrome. When I initiate the dialog by clicking on a specific element, everythin ...

Next.js Configuration Files Explained

Currently, my application is functioning well with the use of Next.js and Next.js API tool for handling requests. The backend is managed through sanity.io which is working smoothly. In my sanity configuration setup, I have a dedicated file named 'san ...

Learn how to execute JavaScript code in Selenium without launching a web browser

I am currently using the Selenium API for web scraping on pages that contain JavaScript code. Is there a way to retrieve the code without having to open a web browser? I am still learning how to use this API Is this even feasible? ...

Modifying PDF files using Angular 4

Encountering a CORS problem in node v8.9.4. Error message - Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200& ...

Python's selenium did not locate the specified CSS element

After transferring the code from Selenium IDE to Python, the selenium test was functioning properly except for clicking on the item and scrolling clicks smoothly on an item. Here is the HTML selenium code: <?xml version="1.0" encoding="UTF-8"?> ...