Skip to content

Instantly share code, notes, and snippets.

@kawsaramin101
Created October 24, 2022 15:47
Show Gist options
  • Save kawsaramin101/5f7c2f0c48c534d8a44e6cfb5e246aa3 to your computer and use it in GitHub Desktop.
Save kawsaramin101/5f7c2f0c48c534d8a44e6cfb5e246aa3 to your computer and use it in GitHub Desktop.
Poll using html css & javascript
<div class="poll">
<div class="question"></div>
<div class="answers"></div>
</div>
let poll =
{
question: "Which is your favorite programming language?",
answers:["Python", "Java", "R", "Php"],
pollcount:100,
answerweight:[60,10,20,10], //sum = 100
selectanswer:-1
};
let polldom =
{
question:document.querySelector(".poll .question"),
answers:document.querySelector(".poll .answers")
};
polldom.question.innerText = poll.question;
polldom.answers.innerHTML = poll.answers.map(function(answer,i){
return(
`
<div class="answer" onclick="markanswer('${i}')">
${answer}
<span class="percentage_bar"></span>
<span class="percentage_value"></span>
</div>
`
);
}).join("");
function markanswer(i)
{
poll.selectanswer = +i;
try{
document.querySelector(".poll .answers .answer.selected")
.classList.remove(".selected");
}
catch(msg){}
document.querySelectorAll(".poll .answers .answer")
[+i].classList.add(".selected");
showresults();
}
function showresults()
{
let answers = document.querySelectorAll(".poll .answers .answer");
for (let i = 0; i < answers.length; i++) {
let percentage = 0;
if (i==poll.selectanswer)
{
percentage = Math.round
(
(poll.answerweight[i] + 1) * 100 / (poll.pollcount + 1)
);
}
else
{
percentage = Math.round
(
(poll.answerweight[i]) * 100 / (poll.pollcount + 1)
);
}
answers[i].querySelector(".percentage_bar").style.width = percentage + "%";
answers[i].querySelector(".percentage_value").innerText = percentage + "%";
}
}
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
background-color: #6b97f6;
}
.poll{
position: absolute;
width: 400px;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
background: #ffff;
border-radius: 25px;
box-shadow: -2px -2px 5px #00000040,
3px 3px 7px #00000040;
}
.poll .question{
padding: 20px;
color: #111;
font-size: 1.5em;
border-bottom: 1px solid #eee;
}
.poll .answers{
padding: 20px;
}
.poll .answers .answer{
position: relative;
width: 100%;
height: 40px;
line-height: 40px;
padding: 0 10px;
border: 1px solid #d4d4d4;
cursor: pointer;
overflow: hidden;
border-radius: 10px;
margin-bottom: 20px;
}
.poll .answers .answer.selected{
border: 2px solid #8f9fe8;
}
.poll .answers .answer span.percentage_value
{
position: absolute;
top: 50%;
right: 0;
transform: translateY(-50%);
width: 40px;
color: #111;
font-size: 15px;
}
.poll .answers .answer span.percentage_bar{
position: absolute;
top: 0;
left: 0;
width: 0;
height: 100%;
background: #97b5f5;
z-index: -2;
transition: width 200ms ease-in-out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment