JSFiddle - React, Tailwind, and code Playground
by Nick Karnik
HTML
<input type=button value="Create TabView" onclick="createTabView(tabContent)"></input>
<input id=tabname type=text value="Tab Name"></input>
<input type=button value="Add Tab" onclick="addTab(tabname.value)"></input>
<div id=tabContent>
</div>
CSS
body,html{
margin:0;
padding:0;
}
#tabContent {
position: absolute;
/* height: 400px; */
width:100%;
/* background-color:violet; */
/* top: 200px; */
}
.tabview {
width:100%;
height:300px;
background-color: red;
position: absolute;
}
.tabs {
list-style: none;
margin: 0;
padding: 0;
height:50px;
position: absolute;
}
.tabs li {
float:left;
border-right: 1px solid rgba(255, 255, 255, 0.4);
color: white;
text-align: center;
padding: 10px 10px 10px 10px;
width: 100px;
height:30px;
}
.tabtop {
top:0;
}
.tabbottom {
top: calc(100% - 50px);
bottom:0;
}
.tabs li:hover {
background-color: yellow;
cursor: pointer;
}
.tabpages {
width:100%;
height: calc(100% - 50px);
background-color: pink;
position: absolute;
}
.tabpagetop {
top: 0;
}
.tabpagebottom {
bottom: 0;
top: 50px;
}
.page {
background-color: orange;
}
JavaScript
var tabPages = {};
function createTabView(div, tabDirection) {
tabDirection = "top";
if (div.children.length > 0) {
return;
}
var tabview = document.createElement('div');
tabview.id = 'tabview';
tabview.classList.add('tabview');
var tabs = document.createElement('div');
tabs.id = 'tabs';
tabs.classList.add('tabs');
var tabpages = document.createElement('div');
tabpages.id = 'tabpages';
tabpages.classList.add('tabpages');
if(tabDirection=="bottom")
{
tabs.classList.add('tabbottom');
tabpages.classList.add('tabpagetop');
}
else
{
tabs.classList.add('tabtop');
tabpages.classList.add('tabpagebottom');
}
tabview.appendChild(tabs);
tabview.appendChild(tabpages);
div.appendChild(tabview);
tabs.addEventListener('click', function (e) {
if (e.target.tagName == 'LI') {
setTab(e.target.textContent);
}
});
}
function setTab(name) {
if (Object.keys(tabPages).indexOf(name) < 0) {
return;
}
if (tabpages.children.length > 0) {
tabpages.removeChild(tabpages.children[0]);
}
tabpages.appendChild(tabPages[name]);
}
function addTabPage(t, page) {
var tab = document.createElement("li");
tab.innerText = t;
tabPages[t] = page;
tabs.appendChild(tab);
setTab(t);
}
function addTab(t) {
if (Object.keys(tabPages).indexOf(t) >= 0) {
return;
}
var page = document.createElement('div');
page.style.width = '100%';
page.style.height = '100%';
page.innerText = t;
page.classList.add('page');
addTabPage(t, page);
}