Home > Blockchain >  Only show one collapse open (Vue 3 / Bootstrap 5)
Only show one collapse open (Vue 3 / Bootstrap 5)

Time:05-24

I'm working with Bootstrap5 and Vue 3. I have multiple buttons and each of them is triggering one collapse.

What I want is that if I open one collapse all other collapse should be closed. But now every collapse will be shown and the other ones are not closing.

I've tried to use data-parent and data-bs-parent but non of this is working.

How can I achive that? Thank You!

<div >
  <div >
    <div >
      <button type="button"  style="height: 200px;" data-bs-toggle="collapse" data-bs-target="#collapse-b1" aria-expanded="false" aria-controls="collapse-b1" data-bs-parent="#myGroup">
        Button 1
      </button>
    </div>
  </div>

  <div >
    <div >
      <button type="button"  style="height: 200px;" data-bs-toggle="collapse" data-bs-target="#collapse-b2" aria-expanded="false" aria-controls="collapse-b2" data-bs-parent="#myGroup">
        Button 2
      </button>
    </div>
  </div>
</div>

<div>
  <div  id="collapse-b1">
    <div >
      Text 1
    </div>
  </div>

  <div  id="collapse-b2">
    <div >
      Text 2
    </div>
  </div>
</div>

CodePudding user response:

A few minor changes to make it work

Your code requires some minor fixes to work correctly. Add the data-bs-parent="#myGroup" attribute to each collapse. And then assign the same id to the parent element of the collapsible elements, i.e., the container.

Note that attribute name has been changed from data-parent in Bootstrap 4 to data-bs-parent in Bootstrap 5. And the parent is the element that contains the collapsible elements and NOT the container of the buttons and links used to toggle.

Additionally, buttons need to have the correct classes applied, e.g., btn-primary and btn-success.

Related SO Question: Collapse other sections when one is expanded

Run the snippet to see how it works:

<div >
  <div >
    <div >
      <button type="button"  style="height: auto;" data-bs-toggle="collapse" data-bs-target="#collapse-b1" aria-expanded="false" aria-controls="collapse-b1">
        Button 1
      </button>
    </div>
  </div>

  <div >
    <div >
      <button type="button"  style="height: auto;" data-bs-toggle="collapse" data-bs-target="#collapse-b2" aria-expanded="false" aria-controls="collapse-b2">
        Button 2
      </button>
    </div>
  </div>

</div>

<div id="myGroup">  <!-- Add the parent id here -->

  <div  id="collapse-b1"  data-bs-parent="#myGroup">
    <div >
      Text 1
    </div>
  </div>

  <div  id="collapse-b2" data-bs-parent="#myGroup">
    <div >
      Text 2
    </div>
  </div>
  
</div>


<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>

  • Related