Created
November 11, 2019 07:43
-
-
Save jasontwuk/600fc2993f5ff6f9ea6a682485fed075 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<head> | |
<meta charset="utf-8"> | |
<title>Ch15-exercise-Tabs</title> | |
</head> | |
<body> | |
<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 divs = document.getElementsByTagName("div"); | |
let tabButton = document.createElement("tab-button"); | |
document.body.prepend(tabButton); | |
for(let i = 0; i < divs.length; i++){ | |
let button = document.createElement("button"); | |
let text = document.createTextNode(divs[i].getAttribute("data-tabname")); | |
button.appendChild(text); | |
tabButton.appendChild(button); | |
// Set the default status. | |
if(i == 0){ | |
// Set the first button's text color to red. | |
button.style.color = "red"; | |
} else { | |
// Hide all other divs except for the first one. | |
divs[i].style.display = "none"; | |
} | |
tabButton.addEventListener("click", swapTab); | |
function swapTab(event){ | |
// When button's name matches div's data-tabname value. | |
if(event.toElement.innerHTML == divs[i].getAttribute("data-tabname")){ | |
button.style.color = "red"; | |
divs[i].style.display = "block"; | |
// When they are different. | |
} else { | |
button.style.color = "black"; | |
divs[i].style.display = "none"; | |
} | |
} | |
} | |
} | |
asTabs(document.querySelector("tab-panel")); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment