Dan Gravell
Dan Gravell

Reputation: 8275

Using collapse/accordion to make a switchable div

In Bootstrap (v3) is it possible to have two divs which are simply switchable, so one div is shown by default, and a button toggles between the two, so one div is always shown?

It feels like "Collapse" and/or "Accordion" should be able to do this but...

"Collapse" doesn't allow for parent elements, to switch between the two and...

"Accordion" allows all of the panels to be hidden.

The same thing can be accomplished with a bit of JQuery but I'm wondering if some use of the data-* attributes may allow me to avoid any JS. Also, I want to use standard Bootstrap classes as much as possible.

Upvotes: 1

Views: 1236

Answers (1)

tmg
tmg

Reputation: 20413

You can use the toggle method of collapse.

HTML

<button class="btn btn-primary" type="button" id="btn">
   Button
</button>

<div id="grouped">
   <div class="collapse in fade" id="1">
      1. Suspendisse non nisl sit amet
   </div>
   <div class="collapse fade" id="2">
      2. Praesent congue erat at massa
   </div>
</div>

As you see first one is open (has class in). Then with javascript we can toggle them

$("#btn").on("click", function(){
    $("#grouped .collapse").collapse('toggle');
});

Note: fade class is optional but looks better with it, in my opinion.

fiddle

Update without custom javascript

<div id="grouped">
   <button class="btn btn-primary" type="button" id="btn" data-toggle="collapse" data-target=".collapse">
     Button
   </button>

   <div class="collapse in fade" id="1">
      1. Suspendisse non nisl sit amet
   </div>
   <div class="collapse fade" id="2">
       2. Praesent congue erat at massa
   </div>
</div>

fiddle

Upvotes: 2

Related Questions