javascripthtmlcssbootstrap-4bootstrap-accordion

Bootstrap 4 change accordion behaviour


I'm using HTML templates, which are based on Bootstrap 4.3.1 to present my students with learning content. In the current templates, all accordion panels are closed on page load and each accordion panel can be opened regardless of how many others have also been opened.

A working example can be found on this CodePen: https://codepen.io/hagelslag1001/pen/MWGeZJr

The HTML code is as follows:

<h2>Accordion: Group of 2</h2>
<p class="small">Accordion: start copy</p>
<!-- Accordion headings should be changed to respect page hierarchy -->
<div class="accordion shadow mb-5">
   <div class="card">
      <div class="card-header">
         <h2 class="card-title">
            Accordion 1 of 2
         </h2>
      </div>
      <div class="collapse">
         <div class="card-body">
            <p>Insert Accordion 1 of 2 content here.</p>
         </div>
      </div>
   </div>
   <div class="card">
      <div class="card-header">
         <h2 class="card-title">
            Accordion 2 of 2
         </h2>
      </div>
      <div class="collapse">
         <div class="card-body">
            <p>Insert Accordion 2 of 2 content here.</p>
         </div>
      </div>
   </div>
</div>
<p class="small">Accordion: end copy</p>

Is it possible to change this default behaviour so that only one panel can be opened at a time? (i.e. as soon as a new panel is opened, the previously opened panel will automatically close)

The Bootstrap examples use (data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne") to accomplish this for the accordions in these templates

I can't figure out how to accomplish this, since the HTML code for the accordions in these templates look different than the Bootstrap 4 examples, which use either an a or button tag to trigger the collapsible event.


Solution

  • Here is a simpler answer based on your CodePen: https://codepen.io/mrtcntn/pen/MWGeZdP

    According the Bootstrap 4 docs, you need id="accordion" on the top level div and you don't need to give ids like id="accordion_1" and id="accordion_2".

    Therefore I removed the first portion from the JS and added id="accordion" at line 18 in the HTML.