JSFiddle - React, Tailwind, and code Playground
by lid0
HTML
<div id="nav" style="margin:5px;padding:15px;border:1px solid gray">
</div>
<div id="box-container" class="container _a">
</div>
<style id="myStyle"></style>
CSS
body {
font-family: 'Lucida Grande', 'Helvetica Neue', Helvetica, Arial, sans-serif;
padding: 0px;
margin: 0px;
font-size: 13px;
}
.container {
display: flex;
border: 5px solid green;
width: 500px;
max-width: 500px;
background: #d5eddc;
}
.hnd {
display: inline-block;
width: 15px;
height: 100%;
background: blue;
background: #2b2b48;
color: #fff;
text-align: center;
}
.box {
background: #81f542;
width: 15px;
overflow: hidden;
padding-left: 0px;
padding-right: 0px;
padding-top: 0px;
padding-bottom: 0px;
transition: width 1.0s, background 1.5s;
white-space: nowrap;
}
b {
background: #fff;
padding: 10px;
border-radius: 5px;
cursor: pointer;
}
b:hover {
background: #cdcdcd;
padding: 10px;
border-radius: 5px;
cursor: pointer;
}
div {
background: #fff;
margin: 0 auto;
}
JavaScript
var boxContainer = document.getElementById('box-container');
var navEl = document.getElementById('nav');
var myStyle = document.getElementById("myStyle")
var boxCount = 0;
var hndWidth = 15; // see width set in .hnd need to keep in sync
function updateStyles(styleEl) {
var styleStr = ""
var width= boxContainer.clientWidth;
var diff = boxCount*hndWidth;
for (var i = 1; i <= boxCount; i++) {
// we generate style the will match for the child
// only when the parent has the child class as active.
// width is calculated based on the container width
// minus the total number of hnd.
styleStr += `
.container._a${i} div._a${i} {
background: #fff;
width:${width-diff}px;
transition: width background 1.5s;
}
`
}
styleEl.innerHTML = styleStr
}
/**
add a box to container
add a button to select in nav
*/
function addBox(containerEl, navEl) {
boxCount++
var boxEl = document.createElement("div")
var boxIdent = "_a" + boxCount;
// create box
boxEl.classList.add(boxIdent)
boxEl.classList.add("box")
boxEl.innerHTML = `<span class="hnd" >${boxCount}</span>Hello World`
containerEl.appendChild(boxEl)
// create nav button
var btn = document.createElement("b");
btn.addEventListener('click', function() {
changeActive(containerEl, boxIdent)
})
btn.innerHTML = boxCount
navEl.appendChild(btn)
updateStyles(myStyle)
}
/** set the active class on the container */
function changeActive(el, _id) {
el.classList.forEach((v) => {
if (v[0] == "_") { // remove any class with leading _
el.classList.remove(v);
}
})
el.classList.add(_id);
}
//add 4 boxes, and set 4th active
document.addEventListener("DOMContentLoaded", function(event) {
addBox(boxContainer, navEl) // _a1
addBox(boxContainer, navEl) // ...
addBox(boxContainer, navEl)
addBox(boxContainer, navEl) // _a4
changeActive(boxContainer, "_a4")
});