Dan Gravell Dan Gravell - 3 months ago 20
jQuery Question

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.

tmg tmg

You can use the toggle method of collapse.


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

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

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.