In this tutorial you will learn how to show and hide elements with Bootstrap.
Toggle Display of Content with Bootstrap
You can use the Bootstrap collapse JavaScript plugin to easily show and hide (or expand and collapse) specific elements on a web page. Buttons and anchors (i.e. the <button> and <a> elements) are typically used as triggers that are mapped to the elements you want to toggle.
Expand and Collapse Elements via Data Attributes
You can show and hide elements in Bootstrap by clicking on a button or link via data attributes without writing any JavaScript code. Let’s try out an example and see how it actually works:
Example
<!-- Trigger Buttons HTML -->
<a href="#myCollapse" data-bs-toggle="collapse">Toggle Element</a>
<button type="button" class="btn btn-primary" data-bs-toggle="collapse" data-bs-target="#myCollapse">Toggle Element</button>
<!-- Collapsible Element HTML -->
<div class="collapse show" id="myCollapse">
<div class="card card-body">This is a simple example of showing and hiding specific element via data attributes. Click any trigger buttons to toggle this panel.</div>
</div>
We’ve just created a collapsible control without writing any JavaScript code. Well, let’s go through each part of this code one by one for a better understanding.
Explanation of Code
The Bootstrap collapse plugin basically requires the two elements to work properly — the trigger element such as a button or hyperlink, and the collapsible element itself.
- The
data-bs-toggle="collapse"attribute is added to the trigger or controller element along with a attributedata-bs-target(for buttons) orhref(for anchors) to automatically assign control of one or more collapsible elements. - The
data-bs-targetorhrefattribute accepts a CSS selector (such as id selector#myCollapsein our example) to apply the collapse to a specific element. - The class
.collapseis added to the collapsible element (line no-6). - You can optionally add the class
.show(line no-6) to the collapsible element in addition to the class.collapseto make it open by default.
To make the collapsible controls to work in group like accordion menu, you can utilize the Bootstrap card component. See the tutorial on Bootstrap accordion to learn more about it.
Expand and Collapse Elements via JavaScript
You may also expand and collapse elements manually via JavaScript — just call the collapse() Bootstrap method with the id or class selector of the collapsible element.
Example
jQuery JavaScript
<script>
$(document).ready(function(){
$("#myBtn").click(function(){
$("#myCollapse").collapse("toggle");
});
});
</script>