-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPreDifinedQuizes.js
113 lines (101 loc) · 2.87 KB
/
PreDifinedQuizes.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
var quiz = {
// (A) PROPERTIES
// (A1) QUESTIONS & ANSWERS
// Q = QUESTION, O = OPTIONS, A = CORRECT ANSWER
data: [
{
q : "What is the full form of PC?",
o : [
"Persnol Computer",
"Private Car",
"Persnol Corporation",
"Private Componey"
],
a : 1 // arrays start with 0, so answer is 70 meters
},
{
q : "In Which planet do we live?",
o : [
"mars",
"pluto",
"Earth",
"Jupyter"
],
a : 3
}
],
// (A2) HTML ELEMENTS
hWrap: null, // HTML quiz container
hQn: null, // HTML question wrapper
hAns: null, // HTML answers wrapper
// (A3) GAME FLAGS
now: 0, // current question
score: 0, // current score
// (B) INIT QUIZ HTML
init: () => {
// (B1) WRAPPER
quiz.hWrap = document.getElementById("quizWrap");
// (B2) QUESTIONS SECTION
quiz.hQn = document.createElement("div");
quiz.hQn.id = "quizQn";
quiz.hWrap.appendChild(quiz.hQn);
// (B3) ANSWERS SECTION
quiz.hAns = document.createElement("div");
quiz.hAns.id = "quizAns";
quiz.hWrap.appendChild(quiz.hAns);
// (B4) GO!
quiz.draw();
},
// (C) DRAW QUESTION
draw: () => {
// (C1) QUESTION
quiz.hQn.innerHTML = quiz.data[quiz.now].q;
// (C2) OPTIONS
quiz.hAns.innerHTML = "";
for (let i in quiz.data[quiz.now].o) {
let radio = document.createElement("input");
radio.type = "radio";
radio.name = "quiz";
radio.id = "quizo" + i;
quiz.hAns.appendChild(radio);
let label = document.createElement("label");
label.innerHTML = quiz.data[quiz.now].o[i];
label.setAttribute("for", "quizo" + i);
label.dataset.idx = i;
label.addEventListener("click", () => quiz.select(label));
quiz.hAns.appendChild(label);
}
},
// (D) OPTION SELECTED
select: (option) => {
// (D1) DETACH ALL ONCLICK
let all = quiz.hAns.getElementsByTagName("label");
for (let label of all) {
label.removeEventListener("click", quiz.select);
}
// (D2) CHECK IF CORRECT
let correct = option.dataset.idx == quiz.data[quiz.now].a;
if (correct) {
quiz.score++;
option.classList.add("correct");
} else {
option.classList.add("wrong");
}
// (D3) NEXT QUESTION OR END GAME
quiz.now++;
setTimeout(() => {
if (quiz.now < quiz.data.length) { quiz.draw(); }
else {
quiz.hQn.innerHTML = `You have answered ${quiz.score} of ${quiz.data.length} , correctly.`;
quiz.hAns.innerHTML = "";
}
}, 1000);
},
// (E) RESTART QUIZ
reset : () => {
quiz.now = 0;
quiz.score = 0;
quiz.draw();
}
};
window.addEventListener("load", quiz.init);