JSFiddle - React, Tailwind, and code Playground
by dimshik
HTML
<div class="score-bar">
<div class="p1 player yellow"></div>
<div class="p2 player red"></div>
<div class="p3 player green"></div>
<div class="p4 player blue"></div>
</div>
CSS
.score-bar {
height: 400px;
width: 100px;
border: 1px solid black;
position: relative;
}
.player {
width: 100px;
height: 0px;
position: absolute;
bottom: 0;
}
.red {
background-color: red;
}
.green {
background-color: green;
}
.yellow {
background-color: yellow;
}
.blue {
background-color: blue;
}
JavaScript
var capturedArea = [8, 11, 20, 6];
var p1 = document.querySelector('.p1');
var p2 = document.querySelector('.p2');
var p3 = document.querySelector('.p3');
var p4 = document.querySelector('.p4');
var players = [p1, p2, p3, p4];
// ignore this function, its only for animation
var interval = setInterval(function() {
for (var i = 0; i < capturedArea.length; i++) {
capturedArea[i] = capturedArea[i] + 1;
}
var total = 0;
for (var i = 0; i < capturedArea.length; i++) {
total = total + capturedArea[i];
}
if (total > 100) {
clearInterval(interval);
return;
}
updateScoreBar(capturedArea, players);
}, 200);
// this is the update function
function updateScoreBar(capturedArea, players) {
for (var i = 0; i < capturedArea.length; i++) {
var player = players[i];
// updating the height of the box
player.style.height = capturedArea[i] + '%';
var bottomPos = 0;
// updating the position of the box accoring to the others
for (var j = 0; j < i; j++) {
bottomPos = bottomPos + capturedArea[j];
}
player.style.bottom = bottomPos + '%';
}
}