a closing button for collapsing all expanded accordion sections in Bootstrap

Is it possible to create a button that closes all currently opened accordion items, while still retaining the toggle functionality? I know it might seem strange since accordions typically have toggles built in, but in my case, I need an external button to close any open accordion item.

I'm hoping someone here can provide a solution. Thank you!

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container py-3">
<div class="accordion" id="accordionExample">
  <div class="card">
    <div class="card-header" id="headingOne">
      <h5 class="mb-0">
        <button class="btn btn-link" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
          Collapsible Group Item #1
        </button>
      </h5>
    </div>

    <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordionExample">
      <div class="card-body">
        Content for accordion item 1.
      </div>
    </div>

  </div>
  
  <div class="card">
    <div class="card-header" id="headingTwo">
      <h5 class="mb-0">
        <button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
          Collapsible Group Item #2
        </button>
      </h5>
    </div>
    
    <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionExample">
      <div class="card-body">
        Content for accordion item 2.
      </div>
    </div>

  </div>
  
  <div class="card">
    <div class="card-header" id="headingThree">
      <h5 class="mb-0">
        <button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
          Collapsible Group Item #3
        </button>
      </h5>
    </div>

    <div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordionExample">
      <div class="card-body">
        Content for accordion item 3.
      </div>
    </div>

  </div>

</div>

<br>

<a class="btn btn-primary" href="#" role="button">Button Close</a>

</div>

Answer №2

Dynamic HTML:

<div class="text-right">
<button class="btn close-button">
Close
</button>

Using jQuery:

$(document).ready(function(){
$(".close-button").on('click', function () {
   $('#accordionExample').find('.card .collapse').removeClass('show'); /* This code closes the currently open accordion */
});
});

Answer №3

When you toggle the according, various actions are triggered:

The content is hidden using the class .collapse

To display the content, the class .collapse.show is used

To close an expanded according after the user clicks the close button, simply remove the show class.

$(document).ready(function() {
  $(".close-button").on('click', function() {
    $('#accordionExample').find('.card .collapse.show').removeClass('show'); /* this closes the opened accordion */
  });
});

Visit this link for a live example on jsFiddle

Answer №4

Custom Solution for Bootstrap 5

The current solutions effectively close the panel, but fail to rotate the chevron icon accordingly. Here is a fresh approach: Please Note: Run the code snippet below to witness this solution in action.

$(document).ready(function() {
    // Identify the open panel and retrieve its id.
    const id = $(".collapse.show").attr('id');
    if (id) {
      // Simulate a click on the element related to this id.
      $("[data-bs-target='#" + id + "']").click();
    }
});

$(document).ready(function() {
  $("#btn-close").on('click', function() {
    const id = $(".collapse.show").attr('id');
    if (id) {
      $("[data-bs-target='#" + id + "']").click();
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="85e7eaeaf1f6f1f7e4f5c5b0abb7abb6">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://getbootstrap.com/docs/5.2/assets/css/docs.css" rel="stylesheet">
  <title>Bootstrap Example</title>
  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f7d70706b6c6b6d7e6f5f2a312d312c">[email protected]</a>/dist/js/bootstrap.bundle.min.js"></script>
</head>

<body class="p-3 m-0 border-0 bd-example">

  <!-- Example Code -->

  <a id="btn-close" class="btn btn-primary" href="#" role="button">Button Close</a>

  <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> It is shown 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="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.
        </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>

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

How can you determine in Chrome when the content of an iframe has been modified by using document.write?

When working with iFrames in different browsers, there can be challenges. For example, in Internet Explorer (IE), we can effectively use the onreadystatechange event to track changes in an iFrame's content when using document.write. However, this meth ...

Learning how to access JavaScript variables within a Ruby on Rails view

Our team has been working on a javascript code that captures the URL of a selected image and stores it in a JavaScript variable called "src". The goal is to access this variable within a Rails view in order to obtain the ID of the selected image. We attemp ...

Error when parsing JSON due to the presence of backslashes within the serialized object

When trying to call a server side function and parse the response in client side using JavaScript and Ajax, I encountered a parse error. It seems that the issue lies with the backslash that the JavaScriptSerializer adds to serialize the object. The respons ...

The addClass, removeClass, and css functions in jQuery are malfunctioning

I stumbled upon this website and I am looking to switch the font color from black to white. I attempted various methods but unfortunately, none of them seemed to work: Implementing jQuery's addClass function (to add a class to the SPAN tag) Uti ...

RoR: Utilizing JQuery and Ajax for seamless resource requests in web

Being a Ruby on Rails fan, I have been exploring tutorials on incorporating AJAX into my projects. After trying out this particular tutorial, I found myself running into some issues. Despite understanding the code, when I slide the stock-list on my compute ...

I encountered a blank page issue when incorporating ui.bootstrap into my controller within Angular

After attempting to utilize angular bootstrap in my project, I encountered an issue where adding the dependency in my controller and starting the server with grunt serve resulted in a blank page. Take a look at the bower components in the screenshot provid ...

An Alternative Approach for Executing a Function within an AngularJS Directive

I am currently working on a unique element directive that displays a user's picture and name. This directive has various configuration attributes, one of which is the uc-on-hover attribute. The purpose of this attribute is to determine what element sh ...

Exploring the internet and its elements through DOM using getElementById

When using Internet Explorer 8, I encountered an issue where the getElementById method does not return DOM elements but plain elements when trying to copy a Div from a parent window to a pop-up. As a result, calling appendChild on those types of items resu ...

use bootstrap to align text vertically according to the image

I am trying to figure out how to center a text vertically next to an image. While I know how to align text horizontally using text-center in bootstrap, I am unsure about how to align it vertically. Is there a way to accomplish this using bootstrap? < ...

Learn how to dynamically disable a button using jQuery within the Materialize CSS framework

While attempting to disable a button in Materialize CSS using jQuery, I encountered an issue. Despite following the documentation found here, it seems that simply adding the 'disabled' class does not automatically disable the button as expected. ...

Mesh in threejs does not include the customDepthMaterial property when outputting to scene.toJSON

I have been working on creating an object with the following code: const geometry = new THREE.SphereBufferGeometry(2,100,100); const material = new THREE.MeshPhongMaterial({ map: myImage, transparent: true, side: THREE.DoubleSide, opacity: ...

What are some effective ways to utilize CSS translateZ?

I'm attempting to create a new layer of content with CSS, but I'm having trouble adjusting the depth of the element using the translateZ property. I tried using some codepen code to achieve a 3D effect. Below is the HTML, CSS, and Javascript cod ...

Tips for verifying that a file has not been selected in Croppie

Whenever I use croppie to crop images on my website, everything works fine when I select an image and upload it. But if I try to crop and upload without selecting an image, a black image gets uploaded instead. How can I validate if the file upload is empty ...

Issue with the statement not being recognized for counting the space bar

I created a counter but I'm having trouble incorporating if statements For example: if (hits == 1) {alert("hello world1")} if (hits == 2) {alert("hello world2")} if (hits == 3) {alert("hello world3")} if (hits == 4) {alert("hello world4")} This is t ...

The specified number of columns and width values are being disregarded

The Challenge While using the CSS column-property to create columns on my webpage, I have encountered some unusual behavior with the layout engine. Specifically, I have set up the following styling: body { padding: 0; background-color: black; margi ...

Content on the right floating underneath content on the left

Here is the HTML code snippet I am working with: <div id="main_content"> <div id="left_side> <h1> MY BIG HEADER </h1> </div> <div id="content_area"> SOME CONTENT HERE SOME CONTENT HERE S ...

AngularJs - Customizable dynamic tabs that automatically adapt

Below is the HTML code snippet: <div> <ul data-ng-repeat ="tab in tabs"> <li data-ng-class="{active: tab.selected == 'true'}" message-key="Tab"> </li> </ul> </div> As shown ...

Verify whether the element within an iFrame contains any content

After conducting extensive research, I have been unable to find a satisfactory answer to my question. Therefore, I am reaching out to see if anyone has the knowledge I seek. The Goal: I aim to check the contents within an iFrame and determine whether it ...

The content of one div is encroaching on another div's space

I'm having trouble with my div text overlapping in unexpected ways. The source of the text is a JS file, so it may not appear correctly here. The text in the div.subheader class keeps overlapping into the div.resource class, which is causing layout i ...

"Troubleshooting: NuxtJs vue-flip feature stuck on front side, not rotating to

I have recently installed the vue-flip plugin in a NuxtJs (VueJS) project that I created using the command: npx create-nuxt-app <project-name>. In the index.vue file, I simply added: <vue-flip active-click="true"> <div slot="front"> ...