-
Notifications
You must be signed in to change notification settings - Fork 2
/
tabs.js
57 lines (51 loc) · 1.74 KB
/
tabs.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
export default class Tabs {
static instances = new WeakMap();
constructor(root) {
Tabs.instances.set(root, this);
this.root = root;
this.tabList = root.querySelector('[role="tablist"]');
this.panels = root.querySelectorAll('[role="tabpanel"]');
this.selectedTab = null;
for (let tab of this.tabList.children) {
tab.addEventListener('mousedown', () => this.change(tab));
if (!tab.getAttribute('aria-selected')) {
tab.setAttribute('tabindex', -1);
} else {
this.selectedTab = tab;
}
}
this.tabList.addEventListener('keydown', e => {
if (this.selectedTab) {
if (e.key === 'ArrowRight' && this.selectedTab.nextElementSibling) {
this.change(this.selectedTab.nextElementSibling);
} else if (e.key === 'ArrowLeft' && this.selectedTab.previousElementSibling) {
this.change(this.selectedTab.previousElementSibling);
}
}
});
}
change(tab) {
const tabPage = document.getElementById(tab.getAttribute('aria-controls'));
for (let other of this.tabList.children) {
other.setAttribute('aria-selected', false);
other.setAttribute('tabindex', -1);
}
tab.setAttribute('aria-selected', true);
tab.setAttribute('tabindex', 0);
tab.focus();
this.selectedTab = tab;
this.panels.forEach(p => p.setAttribute('hidden', true));
tabPage.removeAttribute('hidden');
}
static initDomElements() {
window.addEventListener('DOMContentLoaded', () => {
const tabContainers = document.getElementsByClassName('tabs');
for (const tabContainer of tabContainers) {
if (!Tabs.instances.has(tabContainer)) {
new Tabs(tabContainer);
}
}
});
}
}
Tabs.initDomElements();