JSFiddle - React, Tailwind, and code Playground
by Prathameshsb
HTML
<div id="choices">
<div class="choice">
<div class="label">
<p>Choice 1</p>
<button data-choice="1">Vote</button>
</div>
<div class="result">
<div class="bar" data-choice="1"></div>
</div>
</div>
<div class="choice">
<div class="label">
<p>Choice 2</p>
<button data-choice="2">Vote</button>
</div>
<div class="result">
<div class="bar" data-choice="2"></div>
</div>
</div>
<div class="choice">
<div class="label">
<p>Choice 3</p>
<button data-choice="3">Vote</button>
</div>
<div class="result">
<div class="bar" data-choice="3"></div>
</div>
</div>
</div>
CSS
.choice {
display: flex;
width: 100%;
}
.result {
height: auto;
width: 100%;
display: flex;
flex-direction: column;
justify-content: center;
}
.bar {
width: 100%;
height: 20px;
}
.bar[data-choice="1"] {
background-color: #ff5757;
}
.bar[data-choice="2"] {
background-color: #8aff8a;
}
.bar[data-choice="3"] {
background-color: #57a5ff;
}
.label {
width: 70px;
text-align: center;
}
JavaScript
var buttons = document.querySelectorAll(".choice button"),
tally = {
1: 0,
2: 0,
3: 0,
total: 0
};
function vote(choice) {
tally[choice]++;
tally["total"]++;
console.log(tally);
}
function barPercentage(node, tally) {
var choice = node.dataset.choice;
if (tally[choice])
return tally[choice]/tally["total"] * 100;
return 0;
}
function renderBars() {
var bars = document.getElementsByClassName("bar");
for (var i = 0; i < bars.length; i++) {
var percentage = barPercentage(bars[i], tally);
console.log(percentage)
bars[i].style.width = percentage.toString() + "%";
}
}
function setup() {
// Set up event listeners
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function(e) {
vote(e.target.dataset["choice"]);
renderBars();
});
}
renderBars();
}
setup();