How to use the Bootstrap 4 collapse as a button
Overview
The collapse plugin is used to hide or show another element or the content contained by those elements. This is used specifically to reduce the space taken by the content. For instance, it could be used for frequently asked questions (FAQs) or the reviews posted by customers.
How to implement it
This functionality is implemented by either using a link or a button. In this shot, we'll discuss collapse as a button.
To hide the content through a button, we have to use the data-target attribute along with data-toggle equals to collapse.
Syntax
<buttonclass="btn btn-success"type="button"data-toggle="collapse"data-target="#myCollapseExample"aria-expanded="false"aria-controls="myCollapseExample">//Button_Name_Here</button>
Attributes
data-toggle="collapse": Data toggle is basically used to inform the bootstrap to perform which functionality or activity. For instance, here it is telling that collapsing activity should be performed.data-target="#myCollapse": Data target is used to inform bootstrap about which element is going to open after the action is performed.aria-expanded= "false": This is used to basically define the initial stage of the element. For example, by default, if we want to set the element to be closed or collapsed, then the value will be false. However, if we want to set the element as opened or expanded, the value foraria-expandedwill betrue.aria-controls: This contains the address or the ID of the element which will be collapsed or shown.
Example
Next, let's have a demo code to show the working of a button as collapse:
Explanation
- Line 1–6: We add the basic starting tags; they may vary from editor to editor.
- Line 9–11: We close the opened tags and add Bootstrap’s JavaScript mandatory plugins for running the programs. These may vary according to the versions of the Bootstrap and IDE we're using.
- Line 14: We use the
<p>element and define the<a>tag.href=#myCollapseis the ID of the element on which the action will be performed along withrole= "button".
- Line 15: We define a button using the
<button>element with the above-described attributes.
- Line 17: We add a
<div>tag. It will contain the content that has to be shown or hidden upon action. We assign the class,collapse, and define the ID of<div>tomyCollapse.