-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
113 lines (95 loc) · 2.92 KB
/
script.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
const questions = [
{
question: "Who is the first President of India ?",
answers: [
{ text: "Jwahar Lal Nehru", correct: false },
{ text: "Mahatma Gandhi", correct: false },
{ text: " Dr. Rajendra Prasad", correct: true },
{ text: "Indira Gandhi", correct: false },
]
},
{
question: "Name the national animal of India ?",
answers: [
{ text: "Peacock", correct: false },
{ text: "Tiger", correct: true },
{ text: " Cheetah", correct: false },
{ text: "Lion", correct: false },
]
}
];
const questionelement = document.getElementById("question");
const ansbuttons = document.getElementById("answer-buttons");
const nextbutton = document.getElementById("next-button");
let currentquestionindex = 0;
let score = 0;
function startquiz() {
currentquestionindex = 0;
score = 0;
nextbutton.innerHTML = "Next";
showquestion();
}
function showquestion() {
resetstate();
let currentquestion = questions[currentquestionindex];
let questionno = currentquestionindex + 1;
questionelement.innerHTML = questionno + "." + currentquestion.question;
currentquestion.answers.forEach(answer => {
const button = document.createElement("button");
button.innerHTML = answer.text;
button.classList.add("btn");
ansbuttons.appendChild(button);
if (answer.correct) {
button.dataset.correct = answer.correct;
}
button.addEventListener("click", selectanswer);
});
}
function resetstate() {
nextbutton.style.display = "none";
while (ansbuttons.firstChild) {
ansbuttons.removeChild(ansbuttons.firstChild);
}
}
function selectanswer(e) {
const selectedbtn = e.target;
const iscorrect = selectedbtn.dataset.correct === "true";
if (iscorrect) {
selectedbtn.classList.add("correct");
score++;
}
else {
selectedbtn.classList.add("incorrect");
}
Array.from(ansbuttons.children).forEach(button => {
if (button.dataset.correct === "true") {
button.classList.add("correct");
}
button.disabled = true;
});
nextbutton.style.display = "block";
}
function showscore() {
resetstate();
questionelement.innerHTML = "You scored" + score + "out of " + questions.length;
nextbutton.innerHTML = "Play Again";
nextbutton.style.display = "block";
}
function handlenextbutton() {
currentquestionindex++;
if (currentquestionindex < questions.length) {
showquestion();
}
else {
showscore();
}
}
nextbutton.addEventListener("click", () => {
if (currentquestionindex < questions.length) {
handlenextbutton();
}
else {
startquiz();
}
})
startquiz();