Skip to content

Instantly share code, notes, and snippets.

@adactio
Last active March 8, 2024 07:07
Show Gist options
  • Save adactio/c863130a5a5a8781b50c to your computer and use it in GitHub Desktop.
Save adactio/c863130a5a5a8781b50c to your computer and use it in GitHub Desktop.
Show and hide content with "aria-controls" buttons.
// Licensed under a CC0 1.0 Universal (CC0 1.0) Public Domain Dedication
// http://creativecommons.org/publicdomain/zero/1.0/
(function (win, doc) {
'use strict';
if (!doc.querySelectorAll || !win.addEventListener) {
// doesn't cut the mustard.
return;
}
var toggles = doc.querySelectorAll('[aria-controls]');
var togglecount = toggles.length;
var toggleID;
var togglecontent;
var i;
var target;
for (i = 0; i < togglecount; i = i + 1) {
toggleID = toggles[i].getAttribute('aria-controls');
if (doc.getElementById(toggleID)) {
togglecontent = doc.getElementById(toggleID);
togglecontent.setAttribute('aria-hidden', 'true');
togglecontent.setAttribute('tabindex', '-1');
toggles[i].setAttribute('aria-expanded', 'false');
}
}
function toggle(ev) {
ev = ev || win.event;
target = ev.target || ev.srcElement;
if (target.hasAttribute('aria-controls')) {
toggleID = target.getAttribute('aria-controls');
if (doc.getElementById(toggleID)) {
ev.preventDefault();
togglecontent = doc.getElementById(toggleID);
if (togglecontent.getAttribute('aria-hidden') == 'true') {
togglecontent.setAttribute('aria-hidden', 'false');
target.setAttribute('aria-expanded', 'true');
if (target.tagName == 'A') {
togglecontent.focus(); // https://github.com/edenspiekermann/a11y-toggle/issues/10
}
} else {
togglecontent.setAttribute('aria-hidden', 'true');
target.setAttribute('aria-expanded', 'false');
}
}
}
}
doc.addEventListener('click', toggle, false);
}(this, this.document));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment