Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Bootstrap collapse to have element open by default based on condition

I'm working on making an FAQ page and have a bootstrap collapse with the categories of questions as the collapse titles and the questions as the body.
I'm using the same collapse for both the index and question display pages and I am passing a local variable local: { display: boolean } to differentiate.

I loop through the categories collection to make each table row
<% @categories.each_with_index do |category, index| %>

I have conditionals in the class and aria-expanded of the trigger element:
class='<%= "collapsed" if !display || category != @question.category %>'
aria-expanded='<%= category == @question.category %>'
And in the class of the target
class='collapse <%= "show" if display && category == @question.category %>'

The page loads with the correct row open but it doesn't close when triggered.

like image 941
Tyler Zonies Avatar asked Oct 19 '25 17:10

Tyler Zonies


1 Answers

Everything is described in the Bootstrap documentation

To achieve what you need, you have to:

  1. For buttons/headers:
    1. set data-toggle="collapse"
    2. if the content of the target has to be hidden, then set aria-expanded="false"
    3. if the content of the target has to be displayed, then set aria-expanded="true"
  2. For the targets:
    1. set class="collapse" if the target has to be hidden
    2. set class="collapse show" if the target has to be displayed

Here is an example

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<p>
  <a class="btn btn-primary" data-toggle="collapse" href="#multiCollapseExample1" role="button" aria-expanded="false" aria-controls="multiCollapseExample1">Toggle first element</a>
  <button class="btn btn-primary collapsed" type="button" data-toggle="collapse" data-target="#multiCollapseExample2" aria-expanded="false" aria-controls="multiCollapseExample2">Toggle second element</button>
</p>
<div class="row">
  <div class="col">
    <div class="collapse show multi-collapse" id="multiCollapseExample1">
      <div class="card card-body">
        First element content (displayed by the default)
      </div>
    </div>
  </div>
  <div class="col">
    <div class="collapse multi-collapse" id="multiCollapseExample2">
      <div class="card card-body">
        Second element content
      </div>
    </div>
  </div>
</div>
like image 143
MrShemek Avatar answered Oct 22 '25 08:10

MrShemek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!