1

I need to handle panel collapse behavior without using ID or data attributes. Ideally by setting a "collapsible" class on the parent div that can collapse its content, and a click on the heading should trigger the collapse

Here's the target HTML I'd like to write to handle collapse behavior automatically

<div class="panel-group collapse-all-but-one">
    <div class="panel panel-primary panel-collapsible>
        <div class="panel-heading">Click me to collapse</div>
        <div class="panel-body">I will collaaaaaaapse</div>
    </div>
    <div class="panel panel-warning panel-collapsible">
        <div class="panel-heading">Hey another one</div>
        <div class="panel-body">I will close when the other one opens</div>
    </div>
</div>
dan1st
  • 12,568
  • 8
  • 34
  • 67
Cyril Duchon-Doris
  • 12,964
  • 9
  • 77
  • 164

1 Answers1

1

Here's my magic piece of code (the ready stuff ensures compatibility with rails/angularJS)

var ready
ready = function(){
    $(".panel-collapsable")
    .children(".panel-heading")
        .click(function(){
            var group = $(this).parent().parent()
            if (group.hasClass("panel-group one-at-a-time")){
                group.children(".panel").children(".panel-body")
                    .collapse('hide')
            }
            $(this)
                .next('.panel-body')
                .collapse('toggle')
        })
}
$(document).ready(ready);
$(document).on('page:load', ready);

Remember to add some bootstrap classes like .collapse .in or .collapsed to initialize correct behaviour or the first click isn't going to do anything.

<div class="panel-body collapse in">I am expanded on page load</div>
...
<div class="panel-body collapse">I am collapsed on page load</div>
Cyril Duchon-Doris
  • 12,964
  • 9
  • 77
  • 164