-
Notifications
You must be signed in to change notification settings - Fork 0
/
tabs.js
66 lines (51 loc) · 1.62 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
58
59
60
61
62
63
64
65
66
const tabList = document.querySelector('[role="tablist"]');
const tabs = tabList.querySelectorAll('[role="tab"]');
tabList.addEventListener("keydown", changeTabFocus);
tabs.forEach((tab) => {
tab.addEventListener("click", changeTabPanel);
});
let tabFocus = 0;
function changeTabFocus(e) {
const keydownLeft = 37;
const keydownRight = 39;
if (e.keyCode === keydownLeft || e.keyCode === keydownRight) {
tabs[tabFocus].setAttribute("tabindex", -1);
}
if (e.keyCode === keydownRight) {
tabFocus++;
if (tabFocus >= tabs.length) {
tabFocus = 0;
}
}
if (e.keyCode === keydownLeft) {
tabFocus--;
if (tabFocus < 0) {
tabFocus = tabs.length - 1;
}
}
tabs[tabFocus].setAttribute("tabindex", 0);
tabs[tabFocus].focus();
}
function changeTabPanel(e) {
const targetTab = e.target;
const targetPanel = targetTab.getAttribute("aria-controls");
const targetImage = targetTab.getAttribute("data-image");
const tabContainer = targetTab.parentNode;
const mainContainer = tabContainer.parentNode;
tabContainer
.querySelector('[aria-selected="true"]')
.setAttribute("aria-selected", false);
targetTab.setAttribute("aria-selected", true);
hideContent(mainContainer, '[role="tabpanel"]');
showContent(mainContainer, [`#${targetPanel}`]);
hideContent(mainContainer, "picture");
showContent(mainContainer, [`#${targetImage}`]);
}
function hideContent(parent, content) {
parent
.querySelectorAll(content)
.forEach((item) => item.setAttribute("hidden", true));
}
function showContent(parent, content) {
parent.querySelector(content).removeAttribute("hidden");
}