forked from marijnh/Eloquent-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path14_3_tabs.html
More file actions
43 lines (40 loc) · 1.21 KB
/
14_3_tabs.html
File metadata and controls
43 lines (40 loc) · 1.21 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
<!doctype html>
<div id="wrapper">
<div data-tabname="one">Tab one</div>
<div data-tabname="two">Tab two</div>
<div data-tabname="three">Tab three</div>
</div>
<script>
function asTabs(node) {
var tabs = [];
for (var i = 0; i < node.childNodes.length; i++) {
var child = node.childNodes[i];
if (child.nodeType == document.ELEMENT_NODE)
tabs.push(child);
}
var tabList = document.createElement("div");
tabs.forEach(function(tab, i) {
var button = document.createElement("button");
button.textContent = tab.getAttribute("data-tabname");
button.addEventListener("click", function() { selectTab(i); });
tabList.appendChild(button);
});
node.insertBefore(tabList, node.firstChild);
function selectTab(n) {
tabs.forEach(function(tab, i) {
if (i == n)
tab.style.display = "";
else
tab.style.display = "none";
});
for (var i = 0; i < tabList.childNodes.length; i++) {
if (i == n)
tabList.childNodes[i].style.background = "violet";
else
tabList.childNodes[i].style.background = "";
}
}
selectTab(0);
}
asTabs(document.querySelector("#wrapper"));
</script>