Bootstrap 4 | Collapse other sections when one is expanded
15,597
Solution 1
Make use of data-parent
attribute:
<div class="container" id="myGroup">
<p>
<a class="btn btn-primary" data-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample">
content 1
</a>
<button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseExample2" aria-expanded="false" aria-controls="collapseExample2">
Content 2
</button>
</p>
<div class="collapse" id="collapseExample" data-parent="#myGroup">
<div class="card card-body">
Content 1 here
</div>
</div>
<div class="collapse" id="collapseExample2" data-parent="#myGroup">
<div class="card card-body">
Content 2 here
</div>
</div>
</div>
I added the id
to your container and also added the data-parent
to your content sections, referencing this container through the id
.
Solution 2
just put data-parent="#element_parent",
example...
<a class="btn btn-primary" data-toggle="collapse" href="#colla1" role="button" aria-expanded="false" aria-controls="colla1">
content 1
</a>
<button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#colla2" aria-expanded="false" aria-controls="colla2">
Content 2
</button>
<div class="collapse" id="colla1" data-parent="#element_parent">
<nav
your content 1 here
</nav>
</div>
<div class="collapse" id="colla2" data-parent="#element_parent">
<nav
your content 2 here
</nav>
</div>
Author by
Saif
A tech addict Frontend Developer. I develop Interactive websites, web applications, Passion for problem-solving is what got me into code, being able to come up with creative solutions is what makes me stay.
Updated on June 03, 2022Comments
-
Saif about 2 years
I am working on bootstrap 4 Collapse. Wanted to collapse other sections when one is expanded
So far i did is :
HTML
<p> <a class="btn btn-primary" data-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample"> content 1 </a> <button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseExample2" aria-expanded="false" aria-controls="collapseExample2"> Content 2 </button> </p> <div class="collapse" id="collapseExample"> <div class="card card-body"> Content one here </div> </div> <div class="collapse" id="collapseExample2"> <div class="card card-body"> Content 2 here </div> </div>
Live demo: Live Demo
-
Saif about 6 yearsis there any other way o do it. I try with id but i cant use more then one id in one page.
-
SBylemans about 6 yearsYou can use any selector in the
data-parent
attribute, like a class with.myGroup
for instance. Why can't you use multiple id's in a page though? -
Niklas E. about 4 yearsThe accepted answer already said this. Your answer doesn't contribute to the question.