Skip to content

Instantly share code, notes, and snippets.

@davatron5000
Last active September 19, 2021 01:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save davatron5000/863a32d8ce6144f5cf0063fbf75c0603 to your computer and use it in GitHub Desktop.
Save davatron5000/863a32d8ce6144f5cf0063fbf75c0603 to your computer and use it in GitHub Desktop.
Universal Popup Control
[aria-hidden="true"] { display: none; }
<a href="#" aria-haspopup="true" aria-controls="expandable" aria-expanded="false">Make something expand</a>
<div id="expandable" aria-hidden="true">
<h3>Leave a commment</h3>
<form>
<label for="comment">Comment</label>
<textarea id="comment"></textarea>
</form>
</div>
// For use with little popup menus or subnavigation dropdowns.
const popupTriggers = document.querySelectorAll('[aria-haspopup]');
for(let i = 0; i<popupTriggers.length; i++) {
let popupTrigger = popupTriggers[i];
let popupTarget = document.getElementById(popupTrigger.getAttribute('aria-controls'));
popupTrigger.addEventListener('click', function( event ){
event.preventDefault();
if(popupTrigger.getAttribute('aria-expanded') === "true") {
popupTrigger.setAttribute('aria-expanded', 'false');
popupTarget.setAttribute('aria-hidden', 'true');
// TODO: Set focus to previous focus
} else {
popupTrigger.setAttribute('aria-expanded', 'true');
popupTarget.setAttribute('aria-hidden', 'false');
popupTarget.querySelector('[tabindex="0"], input, textarea, select, button, a').focus();
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment