forked from edenspiekermann/a11y-toggle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patha11y-toggle.js
69 lines (50 loc) · 1.95 KB
/
a11y-toggle.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
(function () {
'use strict';
var internalId = 0;
function $ (selector) {
return Array.prototype.slice.call(document.querySelectorAll(selector));
}
function closest (el, selector) {
if (el.closest) return el.closest(selector);
var matches = el.webkitMatchesSelector
? 'webkitMatchesSelector'
: (el.msMatchesSelector ? 'msMatchesSelector' : 'matches');
while (el) {
if (el.nodeType === 1 && el[matches](selector)) {
console.log(el);
return el;
}
el = el.parentNode;
}
return null;
}
var togglesMap = $('[data-a11y-toggle]').reduce(function (acc, toggle) {
var targetId = toggle.getAttribute('data-a11y-toggle');
toggle.id || toggle.setAttribute('id', 'a11y-toggle-' + internalId++);
toggle.hasAttribute('aria-expanded') || toggle.setAttribute('aria-expanded', true);
toggle.setAttribute('aria-controls', targetId);
acc['#' + targetId] = acc['#' + targetId] || [];
acc['#' + targetId].push(toggle);
return acc;
}, {});
var targetsMap = $(Object.keys(togglesMap)).reduce(function (acc, target) {
var labelledby = togglesMap['#' + target.id].map(function (toggle) {
return toggle.id;
}).join(' ');
target.hasAttribute('aria-hidden') || target.setAttribute('aria-hidden', false);
target.hasAttribute('aria-labelledby') || target.setAttribute('aria-labelledby', labelledby);
acc[target.id] = target;
return acc;
}, {});
document.addEventListener('click', function (event) {
var toggle = closest(event.target, '[data-a11y-toggle]');
var target = toggle && targetsMap[toggle.getAttribute('aria-controls')];
if (!target) return false;
var isExpanded = target.getAttribute('aria-hidden') === 'false';
var toggles = togglesMap['#' + target.id];
target.setAttribute('aria-hidden', isExpanded);
toggles.forEach(function (toggle) {
return toggle.setAttribute('aria-expanded', !isExpanded);
});
});
})();