forked from marijnh/Eloquent-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path15_3_tabs.html
More file actions
33 lines (29 loc) · 975 Bytes
/
15_3_tabs.html
File metadata and controls
33 lines (29 loc) · 975 Bytes
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
<!doctype html>
<tab-panel>
<div data-tabname="one">Tab one</div>
<div data-tabname="two">Tab two</div>
<div data-tabname="three">Tab three</div>
</tab-panel>
<script>
function asTabs(node) {
let tabs = Array.from(node.children).map(node => {
let button = document.createElement("button");
button.textContent = node.getAttribute("data-tabname");
let tab = {node, button};
button.addEventListener("click", () => selectTab(tab));
return tab;
});
let tabList = document.createElement("div");
for (let {button} of tabs) tabList.appendChild(button);
node.insertBefore(tabList, node.firstChild);
function selectTab(selectedTab) {
for (let tab of tabs) {
let selected = tab == selectedTab;
tab.node.style.display = selected ? "" : "none";
tab.button.style.color = selected ? "red" : "";
}
}
selectTab(tabs[0]);
}
asTabs(document.querySelector("tab-panel"));
</script>