Accessible Accordion/Collapser Component – collapse.js

Category: Accordion , Javascript | September 10, 2021
Author:mrdestructicity
Views Total:432 views
Official Page:Go to website
Last Update:September 10, 2021
License:MIT

Preview:

Accessible Accordion/Collapser Component – collapse.js

Description:

A Vanilla JavaScript library to help create highly customizable and fully accessible accordions & collapsible/expandable elements.

How to use it:

1. Add stylesheet collapse.css and JavaScript collapse.js to the page.

<link href="collapse.css" rel="stylesheet" />
<script src="collapse.js"></script>

2. The HTML structure for the accordion/collapser.

<div class="collapse" id="collapse-demo">
  <h2 class="collapse__heading">
    <button class="collapse__button" id="section1a" disabled>
      <span class="collapse__label">
        Section #1
      </span>
      <span class="collapse__icon">
        <svg class="icon icon-plus" focusable="false"><use xlink:href="#icon-plus"></use></svg>
      </span>
    </button>
  </h2>  
  <div class="collapse__panel">
     <p>Section 1 Content</p>
  </div>
  <h2 class="collapse__heading">
    <button class="collapse__button" id="section2a" disabled>
      <span class="collapse__label">
        Section #2
      </span>
      <span class="collapse__icon">
        <svg class="icon icon-plus" focusable="false"><use xlink:href="#icon-plus"></use></svg>
      </span>
    </button>
  </h2>  
  <div class="collapse__panel">
     <p>Section 2 Content</p>
  </div>
  <h2 class="collapse__heading">
    <button class="collapse__button" id="section3a" disabled>
      <span class="collapse__label">
        Section #3
      </span>
      <span class="collapse__icon">
        <svg class="icon icon-plus" focusable="false"><use xlink:href="#icon-plus"></use></svg>
      </span>
    </button>
  </h2>  
  <div class="collapse__panel">
     <p>Section 3 Content</p>
  </div>
</div>
<!-- SVG Icon -->
<svg aria-hidden="true" style="position: absolute; width: 0; height: 0; overflow: hidden;" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <symbol id="icon-plus" viewBox="0 0 30 32">
    <path d="M30.476 14.629h-13.714v-13.105h-3.048v13.105h-13.714v3.048h13.714v12.8h3.048v-12.8h13.714z"></path>
  </symbol>
</svg>

3. Additionally, you can create extra controls that enable you to expand/collapse all panels.

<ul class="collapse__controls" aria-label="Collapse Controls">
  <li><button class="collapse__all-open">Open All</button></li>
  <li><button class="collapse__all-close">Close All</button></li>
</ul>

4. Enable the collapse component.

window.addEventListener('load', (event) => {
  document.querySelectorAll('.collapse').forEach( function( element ) {
    element.collapse = Object.assign(new Collapse(element));
  });
});

You Might Be Interested In:


Leave a Reply