Collapsible Panels with Bootstrap
Bootstrap collapse offers a great way to dynamically show and hide content on the client. The canonical example is to create an accordion control which only allows a single collapsible control to be open at once. Unfortunately, I think this does a poor job of portraying the full versatility and power of collapsible panels.
Here's an overview of what collapse does and how to start using it.
Basics #
At it's core, here's all we need to collapse anything using Twitter Bootstrap's collapse.js:
Just add
data-toggle="collapse"
and adata-target
to element to automatically assign control of a collapsible element. Thedata-target
attribute accepts a CSS selector to apply the collapse to. Be sure to add the classcollapse
to the collapsible element. If you'd like it to default open, add the additional classin
.
HTML:
``` Click For More InfoKyle Do It Self #
On my 26th birthday, my Mom showed my a list of about 100 words and phrases that I could say by age 3. Apparently, one of my favorite things to say was Kyle Do It Self
. While I would rather let a powerful framework like Bootstrap make my life easier, I still really like at least being to understand what it's doing under the hood. Without any pretty touches, here's the gist of how to implement collapse toggles.
We'll start with the same HTML you would use for bootstrap, but we'll use our own CSS and JS. The only dependency here is on plain old jQuery (and you could pretty easily get rid of that if you wanted too).
HTML:
``` {.xml} Click For More InfoIf it's in the collapse state, we'll hide it, but if we've added the in
class, then we'll restore it to the screen. Some transitions would help smooth this out a little, but that's all we need for now.
CSS:
```css .collapse {display: none; } .in {display: block;} ```Now, we just need to be able to toggle the in
class every time there is a click on the parent. We can listen for clicks on anything that has data-toggle='collapse' with the attribute selector. Then, grab the target selector from the data-target
attribute on the sending element and use it to toggle the class of the collapsible panel.
JavaScript:
```js $("[data-toggle='collapse']").click(function() { var targetSelector = $(this).data("target"); $(targetSelector).toggleClass("in"); }); ```And that's it. Bootstrap helps add transitions and style elements so they are logically grouped together, but