Steps to expand all Bootstrap 5 accordions at once without collapsing any of the currently open ones

I own an accordion

How can I expand all accordion items simultaneously by clicking on a single item?

Consider the following scenario:

Accordion Item #1 is open

Accordion Item #2 is closed

Accordion Item #3 is closed

If we click on item #2 or #3, all three accordions will open (with Accordion #1 remaining open), and then if we click on any Accordion Item again, all three accordions will close at once.

<body>
<link href="https://cdn.jsdelivr.net/npm/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
  
  <div class="container">
    <div class="accordion" id="accordionExample">
       <div class="accordion-item">
         <h2 class="accordion-header" id="headingOne">
           <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
             Accordion Item #1
           </button>
         </h2>
         <div id="collapseOne" class="accordion-collapse collapse show" aria-labelledby="headingOne" data-bs-parent="#accordionExample">
           <div class="accordion-body">
             <strong>This is the first item's accordion body.</strong>
           </div>
        </div>
      </div>
       <div class="accordion-item">
         <h2 class="accordion-header" id="headingTwo">
           <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
              Accordion Item #2
          </button>
        </h2>
        <div id="collapseTwo" class="accordion-collapse collapse" aria-labelledby="headingTwo" data-bs-parent="#accordionExample">
            <div class="accordion-body">
               <strong>This is the second item's accordion body.</strong>
            </div>
         </div>
       </div>
     <div class="accordion-item">
       <h2 class="accordion-header" id="headingThree">
          <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
            Accordion Item #3
         </button>
       </h2>
       <div id="collapseThree" class="accordion-collapse collapse" aria-labelledby="headingThree" data-bs-parent="#accordionExample">
         <div class="accordion-body">
           <strong>This is the third item's accordion body.</strong>
         </div>
       </div>
     </div>
  </div>
  </div>

</body>

@nontechguy Answer edited:

<html>
   <head>
      <script src="https://cdn.jsdelivr.net/npm/bootstrap/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
      <link href="https://cdn.jsdelivr.net/npm/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
   </head>
   <body>
      <div class="accordion" id="accordionPanelsStayOpenExample">
         <div class="accordion-item">
            <h2 class="accordion-header" id="panelsStayOpen-headingOne">
               <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target=".panelsStayOpen">
                 Accordion Item #1
               </button>
            </h2>
            <div id="" class="panelsStayOpen accordion-collapse collapse show">
               <div class="accordion-body">
                  <strong>This is the second item's accordion body.</strong> It is hidden by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
               </div>
            </div>
         </div>
         <div class="accordion-item">
            <h2 class="accordion-header" id="panelsStayOpen-headingTwo">
               <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target=".panelsStayOpen">
                 Accordion Item #2
               </button>
            </h2>
            <div id="" class="panelsStayOpen accordion-collapse collapse">
               <div class="accordion-body">
                  <strong>This is the second item's accordion body.</strong> It is hidden by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
               </div>
            </div>
         </div>
         <div class="accordion-item">
            <h2 class="accordion-header" id="panelsStayOpen-headingThree">
                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target=".panelsStayOpen">
                  Accordion Item #3
               </button>
            </h2>
            <div id="" class="panelsStayOpen accordion-collapse collapse">
               <div class="accordion-body">
                  <strong>This is the third item's accordion body.</strong> It is hidden by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
               </div>
            </div>
         </div>
      </div>
   </body>
</html>

Answer №1

Hopefully, I've made progress on addressing your request! All accordion items will now open and close simultaneously when you click on any of them.

<html>
   <head>
      <script src="https://cdn.custom-js.com/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
      <link href="https://cdn.custom-css.com/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
   </head>
   <body>
      <div class="accordion" id="accordionPanelsStayOpenExample">
         <div class="accordion-item">
            <h2 class="accordion-header" id="panelsStayOpen-headingOne">
               <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target=".panelsStayOpen">
               Accordion Item #1
               </button>
            </h2>
            <div id="" class="panelsStayOpen accordion-collapse collapse">
               <div class="accordion-body">
                  <strong>This is the second item's accordion body.</strong> It is hidden by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
               </div>
            </div>
         </div>
         <div class="accordion-item">
            <h2 class="accordion-header" id="panelsStayOpen-headingTwo">
               <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target=".panelsStayOpen">
               Accordion Item #2
               </button>
            </h2>
            <div id="" class="panelsStayOpen accordion-collapse collapse">
               <div class="accordion-body">
                  <strong>This is the second item's accordion body.</strong> It is hidden by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
               </div>
            </div>
         </div>
         <div class="accordion-item">
            <h2 class="accordion-header" id="panelsStayOpen-headingThree">
               <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target=".panelsStayOpen">
               Accordion Item #3
               </button>
            </h2>
            <div id="" class="panelsStayOpen accordion-collapse collapse">
               <div class="accordion-body">
                  <strong>This is the third item's accordion body.</strong> It is hidden by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
               </div>
            </div>
         </div>
      </div>
   </body>
</html>

Answer №2

Bootstrap doesn't come with built-in functionality for your specific scenario. It's necessary to monitor the show or hide events on the collapse element and manually handle each accordion item. I've tweaked a basic example from the Bootstrap documentation to fit your needs. Is this the kind of solution you're looking for?

const accordion = document.getElementById('accordionExample'),
        accordionCollapses = Array.from(document.querySelectorAll('.accordion-collapse'));

accordionCollapses.forEach((accordionCollapse) => {
  accordionCollapse.addEventListener('show.bs.collapse', (event) => {
    accordionCollapses.forEach((accordionCollapse) => {
      accordionCollapse.className = 'accordion-collapse collapsing';            
      accordionCollapse.style.height = '100%';
      setTimeout(() => accordionCollapse.className = 'accordion-collapse collapse show', 350);
      accordionCollapse.parentElement.querySelector('.accordion-button').className = 'accordion-button';
    });
  });

  accordionCollapse.addEventListener('hide.bs.collapse', (event) => {
    accordionCollapses.forEach((accordionCollapse) => {
      accordionCollapse.className = 'accordion-collapse collapsing';
      accordionCollapse.className = 'accordion-collapse collapse';
      accordionCollapse.parentElement.querySelector('.accordion-button').className = 'accordion-button collapsed';
    });
  });
});
<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4b2924243f383f392a3b0b7e657b6579">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
  </head>

  <body>
    <div class="accordion" id="accordionExample">
      <div class="accordion-item">
        <h2 class="accordion-header" id="headingOne">
          <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
            Accordion Item #1
          </button>
        </h2>
        <div id="collapseOne" class="accordion-collapse collapse show" aria-labelledby="headingOne" data-bs-parent="#accordionExample">
          <div class="accordion-body">
            Less content
          </div>
        </div>
      </div>
      <div class="accordion-item">
        <h2 class="accordion-header" id="headingTwo">
          <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
            Accordion Item #2
          </button>
        </h2>
        <div id="collapseTwo" class="accordion-collapse collapse" aria-labelledby="headingTwo" data-bs-parent="#accordionExample">
          <div class="accordion-body">
            <strong>This is the second item's accordion body.</strong> It is hidden by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow. <strong>This is the second item's accordion body.</strong> It is hidden by default, until the collapse plugin adds the appropriate classes that we use to style each el...
          </div>
        </div>
      </div>
      <div class="accordion-item">
        <h2 class="accordion-header" id="headingThree">
          <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
            Accordion Item #3
          </button>
        </h2>
        <div id="collapseThree" class="accordion-collapse collapse" aria-labelledby="headingThree" data-bs-parent="#accordionExample">
          <div class="accordion-body">
            <strong>This is the third item's accordion body.</strong> It is hidden by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
          </div>
        </div>
      </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dcbeb3b3a8afa8aebdac9ce9f2ecf2ee">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
  </body>

</html>

JSFiddle link provided here.

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

Highly complex regular expressions in nth-check causing inefficiencies during npm installation of react-router-dom

Feeling new and inexperienced with how to react, I attempted to execute the command "npm i react-router-dom" but it ended up stopping the download process and displaying several errors. In my search for a solution, I stumbled upon this reference to some ...

Can we refactor by using a distinct function?

I'm working on a table component that handles several columns in a similar way. I'm wondering if there is a more efficient way to optimize this code, perhaps by creating a separate function for it? import useTableStyles from 'admin/compo ...

Ways to stop MongoDB from getting locked

I have a write query that fetches data from a source every minute. However, I also have an application that needs to access this database. I don't necessarily need the new data instantly. The write query is causing a database lock, resulting in the n ...

Using JavaScript with JSON in Facebook

Is it possible to assign the height of a document to a variable called H? If so, how can I do this? var H = document.height; var p = { width: 520, height: H }; FB.Canvas.setSize(p); In JavaScript, how can I achieve this? The expression height: H did not ...

Coordinating Multiple Angular $http Requests using $q and Managing Errors with $q.catch

Struggling with understanding the correct utilization of Angular's $q and JavaScript's promise API. As a newcomer to Javascript, it's possible I'm making a syntax error. This question appears similar, but isn't an exact duplicate. ...

The index falls outside the acceptable range

I've encountered a problem with the Tone.Analyzer in Safari 10.1. When setting the Tone.Analyzer with a size > Math.pow(2, 10) (1024), I'm faced with the following error: IndexSizeError (DOM Exception 1): The index is not in the allowed range. ...

Having trouble getting @vercel/ncc to work, keeps throwing a "Module not found" error

Recently, I have been attempting to follow a tutorial on creating custom GitHub actions using JavaScript from here. The tutorial suggests using the @vercel/ncc package to compile code into a single file if you prefer not to check in your node_modules folde ...

How to assign a property to an object within an array in VueJS?

Currently, I am creating a small list that includes car companies with an option for users to select their favorite one. Within this list, there is an array of objects containing the name and a property called starred. I have a method named setStarred whic ...

Material-UI web application experiencing crashes due to worn-out cards, resulting in element type being declared as invalid and raising an error

After reviewing numerous similar SO questions, it appears that the issue always comes down to problems with imports. Typically, these involve mistyped import destinations or missing braces, but I have double-checked and found no such issues in my code. ht ...

"Debugging a simple demonstration showcasing NodeJS, AngularJS, and Express

Currently, I am following an online tutorial to learn a new concept. I have reached the part where I need to display data using HTTP GET from the controller, while the sample data is stored in the server file. I managed to fetch the data from the controlle ...

Why is the error message "Invalid field name: '$conditionalHandlers' in 'collaborators..$conditionalHandlers'" popping up now?

Currently, in my Node/Express/Mongoose application (latest versions), I am working on a feature that involves "Projects" with a list of "collaborators" identified by the IDS of "Users". To simplify complex aggregations, I have decided to store these IDS as ...

Error: Unable to find the definition for Image (Next.js)

This new component in my next js project allows me to write a quote on an image and display it on the canvas. However, I am encountering an issue with the Image() function in JavaScript which typically runs on the browser. It seems that Next.js first execu ...

Storing numerous JSON records into an array by parsing them from a file

As a beginner in JS programming, I have a question that may seem trivial. Despite hours of searching online, I haven't been able to find a solution that works for me. I am dealing with multiple JSON feeds where each URL provides a multilayer JSON rec ...

Implementing a pre-defined value for ajax in ajax programming for beginners

I'm looking for guidance on setting up a hardcoded value for the OnSuccess parameter. The code I'm referencing is not my own, but I believe it may be related to Ajax. I'm a bit confused about it. Specifically, I need to focus on the OnSucce ...

Greetings: Obtaining an array of text within the <td> tags

Here is the HTML Source: <td bgcolor="#ffffbb" colspan=2><font face="Verdana" size=1>2644-3/4<br>QPSK<br><font color="darkgreen">&nbsp;&nbsp;301</font> - 4864</td> I am looking to extract text array wit ...

Press the Button on the Website using an automated script

I am looking for a solution to increase engagement on my website, which has external like buttons from likebtn.com. To incentivize users to utilize the like buttons, I currently have a script in place that randomly assigns likes to various posts. Howe ...

Sending information from Ajax to PHP

Could anyone please explain the script provided above to me? I am attempting to pass the value of $user data so that I can utilize $_REQUEST['user'] within sort.php, but I am encountering difficulties. It seems to be passing in a long URL. $(fun ...

What is the process for making Bootstrap tables editable?

In my current project, I am utilizing Bootstrap version 5. During the development process, I encountered a requirement to make my bootstrap table editable, allowing users to modify cell values as needed. However, I discovered that the x-editable feature, ...

Parsing XML to JSON using JavaScript

I came across this JavaScript function on Stack Overflow that I've been using to convert XML to JSON: function xmlToJson(xml) { try { var obj = {}; if (xml.nodeType == 1) { if (xml.attributes.length > 0) { ...

Remove the ID, class, and other attributes from an HTML string using JavaScript for sanitization purposes

Can someone help me with sanitizing HTML text provided by a user? The HTML code in question is as follows: var htmlStr = `<p id="test" class="mydemo">TEhis is test</p> <pre class="css"> &lt;html> &lt;body cl ...