Get up to 80 % extra points for free! More info:

Lesson 13 - Bootstrap - Collapse and Accordion

In the previous lesson, Bootstrap - Carousels and Progress, we introduced the Carousel presentation component and Progress bars. In today's Bootstrap CSS framework tutorial, we're going to focus on the toggle-able component Collapse and its modification Accordion.

Collapse

To achieve quality user experience, we should display relevant information only and try to hide any unnecessary contents that the user is probably not interested in at the moment. For this purpose, tabs which we've already discussed in the lesson about List groups, are often used. Bootstrap also provides even more universal component for this purpose, Collapse.

Example

Typically, we use Collapse if there's information which in the most cases would occupy too much space in the page but we still want to leave the option of showing it to some users. Displaying of this information can be bound to e.g. a button or a link. This functionality is often used for spoilers where hiding of the content solves the problem of spoiling the answer of a puzzle, of some math problem, or hides the plot explained in some part of a book review.

Since the code is different if we bind Collapse to a button or to a link, let's show the both options. The code below allows the user to display additional shipping payment details.

<p>We charge $5 for shopping.</p>
<p>
    <a class="btn btn-primary" data-toggle="collapse" href="#collapse-example" aria-expanded="false" aria-controls="collapse-example">
        More information
    </a>
    <button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapse-example" aria-expanded="false" aria-controls="collapse-example">
        More information
    </button>
</p>
<div class="collapse" id="collapse-example">
    <div class="card card-body">
        The postage includes a transportation by Fedex, packing, and notifying our operator about packages which haven't been picked up for a longer time.
    </div>
</div>

Don't forget to link Bootstrap's JavaScript to your website. The result in the browser:

Collapse in Bootstrap
collapse.html

As is customary for JavaScript Bootstrap components, we assign a unique id to the element with the .collapse class as well. We use it later in the button selectors so they could hide or show the element. We assign the data-toggle data attribute with the value of collapse to the buttons/links. Depending on the element used, we define the selector either in the href attribute or in the data-target data attribute. The selector can target classes as well so it can hide/show more than one element. The Bootstrap CSS framework recommends to provide additional attributes for screen readers. For displaying more information, a Bootstrap card is used here but, of course, any HTML content could be placed inside.

Classes

JavaScript automatically assigns the following classes to the element:

  • .collapse - The content is hidden
  • .collapsing - The content is hiding or showing (during animation)
  • .collapse.show - The content is shown

Accordion

The Collapse component actually tempts us to implement the "accordion effect". We use this in complex documents where only a part of the content is interesting for us and showing the whole document would only make things confusing. When a part of the accordion opens, the other parts close. This mechanism is often used e.g. for displaying terms of use or laws. To achieve it, we assign Collapse to the headers of several cards, making the body of these cards callapsiable.

<h1>Trade Licensing Act</h1>
<div id="accordion" role="tablist">
    <div class="card">
        <div class="card-header" role="tab" id="header-1">
            <h5 class="mb-0">
                <a data-toggle="collapse" href="#collapse-1" aria-expanded="true" aria-controls="collapse-1">
                    § 404.1003 Employment.
                </a>
            </h5>
        </div>
        <div id="collapse-1" class="collapse show" role="tabpanel" aria-labelledby="header-1" data-parent="#accordion">
            <div class="card-body">
                Employment means, generally, any service covered by social security performed by an employee for his or her employer. The rules on who is an employee and who is an employer are contained in §§ 404.1005 through 404.1010. Section 404.1004 states the general rule on the kinds of work covered as employment. Exceptions to the general rule are contained in §§ 404.1012 through 404.1038 which explain the kinds of work excluded from employment. All of these rules apply to current work unless otherwise indicated.
            </div>
        </div>
    </div>
    <div class="card">
        <div class="card-header" role="tab" id="header-2">
            <h5 class="mb-0">
                <a class="collapsed" data-toggle="collapse" href="#collapse-2" aria-expanded="false" aria-controls="collapseTwo">
                    § 404.1004 What work is covered as employment?
                </a>
            </h5>
        </div>
        <div id="collapse-2" class="collapse" role="tabpanel" aria-labelledby="header-2" data-parent="#accordion">
            <div class="card-body">
                <ul>
                    <li>(a)General requirements of employment. Unless otherwise excluded from coverage under §§ 404.1012 through 404.1038, the work you perform as an employee for your employer is covered as employment under social security if one of the following situations applies:
                    <ol>
                        <li>You perform the work within the United States (whether or not you or your employer are a citizen or resident of the United States).</li>

                        <li>You perform the work outside the United States and you are a citizen or resident of the United States working for -
                        <ol>
                        <li>An American employer; or</li>

                        <li>A foreign affiliate of an American employer that has in effect an agreement covering your work under section 3121(l) of the Code.</li>
                        </ol>
                        <li>You perform the work on or in connection with an American vessel or American aircraft and the conditions in paragraphs (a)(3) (i) and (ii) are met. Your citizenship or residence does not matter. The citizenship or residence of your employer matters only if it affects whether the vessel is an American vessel.
                        <ol>
                            <li>You enter into the contract of employment within the United States or the vessel or aircraft touches at a port or airport within the United States during the performance of your contract of employment on the vessel or aircraft.</li>

                            <li>(ii) You are employed on and in connection with the vessel or aircraft when outside the United States.</li>
                        </ol>
                        <li>Your work is designated as employment or recognized as equivalent to employment under a totalization agreement. (See § 404.1913. An agreement may exempt work from coverage as well as extend coverage to work.)</li>

                        <li>Your work performed after December 31, 1994, is in the employ of an international organization pursuant to a transfer from a Federal agency under section 3582 of title 5 of the United States Code and both the following are met:</li>
                        <ol>
                            <li>Immediately before the transfer, your work for the Federal agency was covered employment; and</li>

                            <li>You would be entitled, upon separation from the international organization and proper application, to reemployment with the Federal agency under section 3582.</li>
                        </ol>
                    </ol>
                </ul>
            </div>
        </div>
    </div>
    <div class="card">
        <div class="card-header" role="tab" id="header-3">
            <h5 class="mb-0">
                <a class="collapsed" data-toggle="collapse" href="#collapse-3" aria-expanded="false" aria-controls="collapse-3">
                    § 404.1005 Who is an employee.
                </a>
            </h5>
        </div>
        <div id="collapse-3" class="collapse" role="tabpanel" aria-labelledby="header-3" data-parent="#accordion">
            <div class="card-body">
                <p>You must be an employee for your work to be covered as employment for social security purposes. You are an employee if you are -</p>
            <ol>
                <li>A corporation officer as described in § 404.1006;</li>

                <li>A common-law employee as described in § 404.1007 (unless you are, after December 31, 1982, a qualified real estate agent or direct seller as described in § 404.1069); or</li>

                <li>An agent-driver or commission-driver, a full-time life insurance salesman, a home worker, or a traveling or city salesman as described in § 404.1008.</li>
            </ol>
            </div>
        </div>
    </div>
</div>

The result:

Collapse in Bootstrap
collapse_accor­dion.html

The code probably doesn't need to be described much because it's just cards which we have already explained in depth in this course. We bind the card headers using unique id selectors with their bodies. The data attributes and .collapse classes ensure that only one card is collapsed at the time.

Bootstrap even allows us to create an accordion using completely custom components, it doesn't have to be cards. The data-children data attribute needs to be assigned to the <div> with the accordion. Into this attribute we specify the selector of all the accordion items. For example the .item value (including the dot) can be placed there. The structure is going to change a little bit, see the following example and eventually its source code as well:

Collapse in Bootstrap
collapse_accor­dion.html

To support screen readers, check that the "aria" attributes are assigned correctly so that the reader would be able to read opened elements only and offer to open the hidden ones.

Collapse can be used for any kind of element, it just needs to be bound correctly, see the first example.

JavaScript

If you needed to react on Collapse from JavaScript in any way, it can be controlled as jQuery plugin providing methods and events as always.

We can initialize it manually instead of using data attributes like this:

$('.collapse').collapse();

Properties

To specify the parent and the button we've used the data-parent and data-toggle data attributes. In JavaScript, we can use properties of the same name without the data- prefix, meaning:

  • parent - If the parent element is specified, all other elements will be closed once one of them is opened. We assign this attribute to the items which are meant to be shown/hidden. The default value is false, we can specify the parent using a selector, jQuery object, or DOM element.
  • toggle - Shows/hides the corresponding element. The default value is true. We set this property to the control elements.

Methods

The methods of this component are called asynchronously as always. Note that when the animation is in progress, other method calls are ignored. The control flow is passed right after the animation starts but before it stops.

We can create collapsible elements in JavaScript like this:

$('#myCollapsible').collapse({
  toggle: false
})

We can call the method with these parameters:

  • "toggle" - Hides/shows the collapsible element, passes the control flow before switching
  • "show" - Shows the collapsible element, passes the control flow before switching
  • "hide" - Hides the collapsible element, passes the control flow before switching
  • "dispose" - Removes collapse

Events

We can handle the following JavaScript events:

  • show.bs.collapse - Is called right after calling the method with the value of "show".
  • shown.bs.collapse - Is called right after the animation displaying the element stops.
  • hide.bs.collapse - Is called right after calling the method with the value of "hide".
  • hidden.bs.collapse - Is called right after the animation hiding the element stops.

We can handle events e.g. like this:

$('#collapsible-item').on('hidden.bs.collapse', function () {
    // some reaction...
});

In the next lesson, Bootstrap - Dropdowns, we'll focus on Dropdown buttons.


 

Previous article
Bootstrap - Carousels and Progress
All articles in this section
Bootstrap
Skip article
(not recommended)
Bootstrap - Dropdowns
Article has been written for you by David Capka Hartinger
Avatar
User rating:
2 votes
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn university David learned IT at the Unicorn University - a prestigious college providing education on IT and economics.
Activities