Source Code:
(back to article)
Submit
Result:
Report an issue
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Accessible Accordion Example</title> <style> .accordion { border: 1px solid #ccc; border-radius: 5px; margin: 20px 0; } .accordion-header { padding: 10px; cursor: pointer; background-color: #f0f0f0; border-bottom: 1px solid #ccc; } .accordion-content { display: none; padding: 10px; } .accordion-content[aria-expanded="true"] { display: block; } </style> </head> <body> <h1>Accessible Accordion Example</h1> <h4>Use your keyboard (Enter or Space key) to toggle the accordion!</h4> <div class="accordion"> <div class="accordion-header" id="accordion-header-1" role="button" aria-controls="accordion-content-1" aria-expanded="false" tabindex="0"> Section 1 </div> <div class="accordion-content" id="accordion-content-1" role="region" aria-labelledby="accordion-header-1"> <p>This is the content of section 1.</p> </div> </div> <div class="accordion"> <div class="accordion-header" id="accordion-header-2" role="button" aria-controls="accordion-content-2" aria-expanded="false" tabindex="0"> Section 2 </div> <div class="accordion-content" id="accordion-content-2" role="region" aria-labelledby="accordion-header-2"> <p>This is the content of section 2.</p> </div> </div> <div class="accordion"> <div class="accordion-header" id="accordion-header-3" role="button" aria-controls="accordion-content-3" aria-expanded="false" tabindex="0"> Section 3 </div> <div class="accordion-content" id="accordion-content-3" role="region" aria-labelledby="accordion-header-3"> <p>This is the content of section 3.</p> </div> </div> <script> document.querySelectorAll('.accordion-header').forEach(header => { header.addEventListener('click', function () { const expanded = this.getAttribute('aria-expanded') === 'true'; this.setAttribute('aria-expanded', !expanded); document.getElementById(this.getAttribute('aria-controls')).style.display = !expanded ? 'block' : 'none'; }); header.addEventListener('keydown', function (event) { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); this.click(); } }); }); </script> </body> </html>