JSFiddle - React, Tailwind, and code Playground
Poll
by Ttt Yyy
HTML
<div id='container'>
<!-- <div class='row'>
<div class='percent'>
%
</div>
<div class='inner'>
<div class='bar' style='width: %'>
Label
</div>
</div>
</div> -->
</div>
CSS
#container {
border: 1px solid #ccc;
padding: 10px;
}
.bar {
border: 1px solid gray;
background-color: #3b5998;
color: black;
/* height: 20px; */
/* white-space: nowrap;
overflow: visible; */
overflow: hidden;
text-overflow: ellipsis;
}
.row {
/* border: 1px solid red; */
display: flex;
/* flex-wrap: wrap;
*/}
.percent {
padding: 0 5px;
/* float: left; */
}
.winner {
color: blue;
}
.winner .bar {
background-color: red;
}
.inner{
margin-left: 10px;
flex: 1 1 auto;
}
JavaScript
const votes = [
{label:'redredredredredredredredredredredredredredredredredredredredredredredredredredredred', count: 5},
{label:'blue', count: 20},
{label:'green', count: 10}
]
const poll = (votes, container) => {
let total = 0;
let max = 0;
votes.forEach((vote) => {
total += vote.count;
max = Math.max(vote.count, max);
});
votes.forEach((vote) => {
let row = document.createElement('div');
row.className = 'row';
if(vote.count === max) {
row.className = 'row winner'
}
let displayPercent = Math.round(vote.count/total * 100);
let cssPercent = Math.round(vote.count/max * 100)
row.innerHTML =`
<div class='percent'>
${displayPercent}%
</div>
<div class='inner' >
<div class='bar' style='width: ${cssPercent}%'>${vote.label}</div>
</div>`
container.appendChild(row)
})
}
poll(votes, document.getElementById('container'))