JSFiddle - React, Tailwind, and code Playground
by Gwyn Milcote
HTML
<button id='reveal-btn'>Reveal answers</button> <button id='reset-btn'>New questions</button>
<div id='js-message'></div>
<div id='quiz-result'></div>
<div id='question-container'></div>
CSS
div, img, button, p {
box-sizing: border-box;
}
#question-container {
margin: 20px auto;
}
#question-container .quiz-question {
border: 1px solid silver;
padding: 5px;
margin-bottom: 10px;
}
.question-correct {
background-color: lightgreen;
}
.question-incorrect {
background-color: lightpink;
}
.question-choices {
display: flex;
flex-flow: row wrap;
justify-content: space-evenly;
margin-top: 5px;
padding: 5px;
background-color: rgba(0, 0, 0, 0.1);
border-radius: 2px;
}
.question-choices .question-choice {
padding: 3px 10px;
border: 1px solid silver;
background-color: #fff;
}
.active-choice:hover {
cursor: pointer;
background-color: #eee;
border: 1px solid grey;
}
.selected-choice {
background-color: silver !important;
border: 1px solid grey !important;
}
.correct-choice {
background-color: lightgreen !important;
border: 1px solid green !important;
}
JavaScript
const questions = [
{
id: 1, text: "aaaaaa",
choices: ["aaa", "bbb", "ccc", "ddd"],
answer: 1
},{
id: 2, text: "bbbbbb",
choices: ["aaa", "bbb", "ccc", "ddd"],
answer: 1
},{
id: 3, text: "cccccc",
choices: ["aaa", "bbb", "ccc", "ddd"],
answer: 4
},{
id: 4, text: "ddddddd",
choices: ["aaa", "bbb", "ccc", "ddd"],
answer: 3
},{
id: 5, text: "eeeeee",
choices: ["aaa", "bbb", "ccc", "ddd"],
answer: 4
},{
id: 6, text: "fffffff",
choices: ["aaa", "bbb", "ccc", "ddd"],
answer: 2
},{
id: 7, text: "gggggg",
choices: ["aaa", "bbb", "ccc", "ddd"],
answer: 3
},{
id: 8, text: "hhhhhh",
choices: ["aaa", "bbb", "ccc", "ddd"],
answer: 2
},{
id: 9, text: "iiiiiii",
choices: ["aaa", "bbb", "ccc", "ddd"],
answer: 4
},{
id: 10, text: "jjjjjjj",
choices: ["aaa", "bbb", "ccc", "ddd"],
answer: 1
},{
id: 11, text: "kkkkkkk",
choices: ["aaa", "bbb", "ccc", "ddd"],
answer: 3
},{
id: 12, text: "lllll",
choices: ["aaa", "bbb", "ccc", "ddd"],
answer: 2
},{
id: 13, text: "mmmmm",
choices: ["aaa", "bbb", "ccc", "ddd"],
answer: 4
},{
id: 14, text: "nnnnn",
choices: ["aaa", "bbb", "ccc", "ddd"],
answer: 1
}
];
function randomNumber(n1, n2){
if(n1 == n2){ return n1; }
let min = n1, max = n2;
if(n1 > n2){ min = n2; max = n1; }
return Math.floor(Math.random() * (max - min + 1) + min);
}
function randomArray(array){
return array[Math.floor(Math.random() * array.length)];
}
class Quiz {
constructor(){
this.generate();
}
/*
* Choose 20 random questions from array.
* Render them with choices.
*/
generate(){
let ids = [];
this.questions...