Turn Headings Into an Accordion
Turns every H3 inside a block with the class "wpide-accordion" into a clickable question that shows or hides the content below it, for FAQs written as plain headings and paragraphs.
Opens WPIDE on
Code
<style>
.wpide-accordion h3 button{all:inherit;display:flex;justify-content:space-between;align-items:center;width:100%;cursor:pointer;}
.wpide-accordion h3 button::after{content:"+";font-weight:400;margin-left:1em;}
.wpide-accordion h3 button[aria-expanded="true"]::after{content:"\2212";}
.wpide-accordion h3 button:focus-visible{outline:2px solid currentColor;outline-offset:3px;}
.wpide-accordion .wpide-accordion__panel[hidden]{display:none;}
</style>
<script>
document.querySelectorAll('.wpide-accordion').forEach(function (box, b) {
box.querySelectorAll(':scope > h3').forEach(function (heading, i) {
var panel = document.createElement('div');
panel.className = 'wpide-accordion__panel';
panel.id = 'wpide-acc-' + b + '-' + i;
panel.hidden = true;
while (heading.nextElementSibling && heading.nextElementSibling.tagName !== 'H3') {
panel.appendChild(heading.nextElementSibling);
}
heading.insertAdjacentElement('afterend', panel);
var button = document.createElement('button');
button.type = 'button';
button.setAttribute('aria-expanded', 'false');
button.setAttribute('aria-controls', panel.id);
while (heading.firstChild) { button.appendChild(heading.firstChild); }
heading.appendChild(button);
button.addEventListener('click', function () {
var open = button.getAttribute('aria-expanded') !== 'true';
button.setAttribute('aria-expanded', open ? 'true' : 'false');
panel.hidden = !open;
});
});
});
</script>
Notes
Add wpide-accordion to a Group block containing H3 headings followed by their answers. Without JavaScript everything stays visible.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.