Last active
September 20, 2018 09:30
-
-
Save reecelucas/f447e54ee30f0361c99e593726064e12 to your computer and use it in GitHub Desktop.
Simple accessible multi-select accordion. Modified from: https://inclusive-components.design/collapsible-sections/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const config = { | |
accordionSelector: "[data-accordion]", | |
headingSelector: "[data-accordion-heading]", | |
buttonSelector: "[data-accordion-button]" | |
}; | |
const setup = accordion => { | |
const headings = [...accordion.querySelectorAll(config.headingSelector)]; | |
if (!headings || headings.length === 0) return; | |
for (const heading of headings) { | |
const accordionBody = heading.nextElementSibling; | |
// Give each <h2> a toggle button child | |
heading.innerHTML = ` | |
<button aria-expanded="false" data-accordion-button> | |
${heading.textContent} | |
</button> | |
`; | |
accordionBody.hidden = true; | |
} | |
}; | |
const onClick = ({ target }) => { | |
if (target && target.matches(config.buttonSelector)) { | |
const button = target; | |
const expanded = button.getAttribute("aria-expanded") === "true"; | |
const accordionBody = button.parentElement.nextElementSibling; | |
button.setAttribute("aria-expanded", !expanded); | |
accordionBody.hidden = expanded; | |
} | |
}; | |
export default () => { | |
const accordions = [...document.querySelectorAll(config.accordionSelector)]; | |
if (!accordions || accordions.length === 0) return; | |
for (const accordion of accordions) { | |
setup(accordion); | |
accordion.addEventListener("click", onClick); | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div data-accordion> | |
<h2 data-accordion-heading>Section 1</h2> | |
<div> | |
<p> | |
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque commodo | |
purus quis mi cursus hendrerit eu eu metus. Aliquam aliquam arcu eget | |
aliquet scelerisque. Pellentesque sodales turpis vitae venenatis vehicula. | |
</p> | |
</div> | |
<h2 data-accordion-heading>Section 2</h2> | |
<div> | |
<p>Nullam tortor metus, tincidunt ut urna id, posuere placerat orci.</p> | |
<p> | |
Ut quis risus dictum risus facilisis imperdiet quis sed eros. Lorem ipsum | |
dolor sit amet, consectetur adipiscing elit. | |
</p> | |
</div> | |
</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment