Hide div by default and show it on click with bootstrap

Here I propose a way to do this exclusively using the Bootstrap framework built-in functionality.

  1. You need to make sure the target div has an ID.
  2. Bootstrap has a class “collapse”, this will hide your block by
    default. If you want your div to be collapsible AND be shown by
    default you need to add “in” class to the collapse. Otherwise the
    toggle behavior will not work properly.
  3. Then, on your hyperlink (also works for buttons), add an href
    attribute that points to your target div.
  4. Finally, add the attribute data-toggle="collapse" to instruct
    Bootstrap to add an appropriate toggle script to this tag.

Here is a code sample than can be copy-pasted directly on a page that already includes Bootstrap framework (up to version 3.4.1):

<a href="#Foo" class="btn btn-default" data-toggle="collapse">Toggle Foo</a>
<button href="#Bar" class="btn btn-default" data-toggle="collapse">Toggle Bar</button>
<div id="Foo" class="collapse">
    This div (Foo) is hidden by default
</div>
<div id="Bar" class="collapse in">
    This div (Bar) is shown by default and can toggle
</div>

Leave a Comment