bootstrap accordion

by johan polson

HTML

<!--

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.8/js/bootstrap.min.js"></script>
-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.8/css/bootstrap.min.css" integrity="sha512-2bBQCjcnw658Lho4nlXJcc6WkV/UxpE/sAokbXPxQNGqmNdQrWqtw26Ns9kFF/yG792pKR1Sx8/Y1Lf1XN4GKA==" crossorigin="anonymous" referrerpolicy="no-referrer" />

<div class="container">

<div class="accordion">
  <div class="accordion-item">
    <h2 class="accordion-header">
      <button id="button" class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-_target="#collapseOne" aria-expanded="_false" aria-controls="collapseOne">
        Accordion Item #1
      </button>
    </h2>
    <div id="collapseOne" class="accordion-collapse collapse" data-bs-parent="#accordionExample">
      <div class="accordion-body">
        <strong>This is the first item’s accordion body.</strong> It is shown by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It’s also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
      </div>
    </div>
  </div>
</div>

</div>

JavaScript

document.addEventListener('DOMContentLoaded', () => {
  const elements = document.getElementsByClassName('accordion-header');
  for (const element of elements) {
    const button = element.getElementsByClassName('accordion-button')[0];
    const target = button.getAttribute('data-bs-target');
    const targetElement = (target == null) ?
      element.nextElementSibling :
      document.querySelector(target);
    const ariaExpanded = button.getAttribute('aria-expanded') !== 'false';
    if (!ariaExpanded){
      button.classList.remove('collapsed');
      targetElement.classList.add('show');
    } 
  
    const SetMef = () => {
      if (targetElement.classList.contains('show')) {
        button.classList.add('collapsed');
        targetElement.classList.remove('show');
      } else {
        button.classList.remove('collapsed');
        targetElement.classList.add('show');
      }
    };

    SetMef();
    // element.addEventListener('click', () => SetMef());
  }
});