-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
76 lines (69 loc) · 2.25 KB
/
Copy pathscript.js
File metadata and controls
76 lines (69 loc) · 2.25 KB
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
70
71
72
73
74
75
76
// Accessible FAQ accordion
// - Each question is a <button> with aria-expanded / aria-controls
// - Keyboard: Tab between buttons, Enter/Space toggles, Esc closes open panel
// - "Expand all" / "Collapse all" controls
// - Deep-linking: opens the accordion for a URL hash matching an answer's id
// or the nearest answer inside a section hash
(function () {
'use strict';
var questions = Array.prototype.slice.call(
document.querySelectorAll('.faq-question')
);
function setOpen(btn, open) {
var panelId = btn.getAttribute('aria-controls');
var panel = document.getElementById(panelId);
if (!panel) return;
btn.setAttribute('aria-expanded', open ? 'true' : 'false');
if (open) {
panel.hidden = false;
} else {
panel.hidden = true;
}
}
function toggle(btn) {
var isOpen = btn.getAttribute('aria-expanded') === 'true';
setOpen(btn, !isOpen);
}
questions.forEach(function (btn) {
btn.addEventListener('click', function () {
toggle(btn);
});
btn.addEventListener('keydown', function (e) {
if (e.key === 'Escape') {
if (btn.getAttribute('aria-expanded') === 'true') {
setOpen(btn, false);
btn.focus();
}
}
});
});
// Expand/Collapse all
var expandAll = document.getElementById('expand-all');
var collapseAll = document.getElementById('collapse-all');
if (expandAll) {
expandAll.addEventListener('click', function () {
questions.forEach(function (b) { setOpen(b, true); });
});
}
if (collapseAll) {
collapseAll.addEventListener('click', function () {
questions.forEach(function (b) { setOpen(b, false); });
});
}
// Open the accordion that matches a URL hash, if any
function openFromHash() {
var hash = window.location.hash.replace('#', '');
if (!hash) return;
var target = document.getElementById(hash);
if (!target) return;
// If the hash points at an answer panel, find its controlling button.
if (target.classList && target.classList.contains('faq-answer')) {
var btn = document.querySelector(
'.faq-question[aria-controls="' + hash + '"]'
);
if (btn) setOpen(btn, true);
}
}
openFromHash();
window.addEventListener('hashchange', openFromHash);
})();