-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
212 lines (186 loc) · 6.84 KB
/
app.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
const question = document.querySelector('.question')
const option1 = document.querySelector('#option-1');
const option2 = document.querySelector('#option-2');
const option3 = document.querySelector('#option-3');
const option4 = document.querySelector('#option-4');
const beginBtn = document.querySelector('.begin-btn');
const selectCategory = document.querySelector('#select-category');
const questionNumber = document.querySelector('.question-number');
const totalQuestions = document.querySelector('.total-questions');
const nextBtn = document.querySelector('.next-btn');
const previousBtn = document.querySelector('.previous-btn');
const restartBtn = document.querySelector('.restart-btn')
const error_msg = document.querySelector('.error-msg');
const display_answer = document.querySelector('.display-answer');
const beginQuiz = document.querySelector('.begin-quiz');
const quizArea = document.querySelector('.quiz-area');
const endArea = document.querySelector('.end-area');
const totalScore = document.querySelector('.total-score');
//global variable
let randomOptions =[]
let currentQuestionIndex = 0;
let opts_input = Array.from(document.getElementsByName('options'));
let quizData = null;
let userScore = 0;
let currentQuestionNumber = 1
let category_id = 18; //default category --> Computer Science
let quizCategory = null;
async function getCategory(){
let url = 'https://opentdb.com/api_category.php'
try {
let category = await fetch(url);
return await category.json();
} catch(error){
console.log(error);
}
}
async function displayCategory(){
quizCategory = await getCategory();
let triviaCategories = quizCategory.trivia_categories;
//displaying cateogry
triviaCategories.forEach(category => {
let option = document.createElement('option')
option.setAttribute('value', `${category.id}`);
option.textContent = category.name;
selectCategory.appendChild(option);
})
}
function updateCategoryID() {
category_id = selectCategory.value;
}
async function getQuizData(){
let url = `https://opentdb.com/api.php?amount=10&category=${category_id}&type=multiple`;
try{
let data = await fetch(url);
if(!data.ok) throw new Error('Failed to fetch data');
return await data.json();
} catch (error) {
console.log(error);
}
}
async function startquiz(){
clearHTML();
updateCategoryID();
beginQuiz.classList.add('hidden');
quizArea.classList.remove('hidden');
endArea.classList.add('hidden')
quizData = await getQuizData();
console.log(quizData);
renderHTML();
}
function renderHTML(){
//remove correct-answer class from previous selected option
opts_input.forEach(opt => opt.nextElementSibling.classList.remove('correct-answer'));
//decoding HTML encoding
const decodeQuestion = decodeHTML(quizData.results[currentQuestionIndex].question);
question.textContent = decodeQuestion;
//questions options
let options = [decodeHTML(quizData.results[currentQuestionIndex].incorrect_answers[0]),
decodeHTML(quizData.results[currentQuestionIndex].incorrect_answers[1]),
decodeHTML(quizData.results[currentQuestionIndex].incorrect_answers[2]),
decodeHTML(quizData.results[currentQuestionIndex].correct_answer),
];
shuffleOptions(options);
//assigning options to HTML element
questionNumber.textContent = currentQuestionNumber;
totalQuestions.textContent = quizData.results.length;
option1.nextElementSibling.textContent = randomOptions[0];
option2.nextElementSibling.textContent = randomOptions[1];
option3.nextElementSibling.textContent = randomOptions[2];
option4.nextElementSibling.textContent = randomOptions[3];
}
function shuffleOptions(options){
while (randomOptions.length < options.length){
let randomItem = options[Math.floor(Math.random()* options.length)]
if(!randomOptions.includes(randomItem)){
randomOptions.push(randomItem)
}
}
}
function nextQuestion(){
let selectedOption = opts_input.find(opt => opt.checked);
let correctAnswer = decodeHTML(quizData.results[currentQuestionIndex].correct_answer);
//condtion if no option is selected
if(!selectedOption){
error_msg.textContent = 'No skipping questions!'
error_msg.classList.remove('hidden');
setTimeout(() => {
error_msg.classList.add('hidden');
}, 1000);
return;
}
//check answer
if(selectedOption.nextElementSibling.textContent === correctAnswer){
userScore ++;
selectedOption.nextElementSibling.classList.add('correct-answer')
} else{
display_answer.textContent = correctAnswer;
display_answer.classList.remove('hidden');
setTimeout(() => {
display_answer.classList.add('hidden');
renderHTML()
},1000);
}
setTimeout(() => {
currentQuestionNumber ++;
currentQuestionIndex ++;
randomOptions = [];
clearSelectedOption();
if(currentQuestionIndex < quizData.results.length){
renderHTML();
} else{ // to handle end of quiz
quizArea.classList.add('hidden')
endArea.classList.remove('hidden');
console.log('end of quiz!')
console.log(`Your total score is: ${userScore}`)
totalScore.textContent = `Score: ${userScore} out of ${quizData.results.length}`
}
}, 1000);
}
function previousQuestion(){
if(currentQuestionIndex <= 0){
error_msg.textContent = 'This is the first question'
error_msg.classList.remove('hidden');
setTimeout(() => {
error_msg.textContent = 'Please select an option.'
error_msg.classList.add('hidden');
}, 1000);
return;
}
currentQuestionNumber --;
currentQuestionIndex --;
randomOptions =[];
clearSelectedOption();
renderHTML();
}
function clearSelectedOption() {
opts_input.forEach(opt => opt.checked = false);
}
//for decomding HTML-encoding
function decodeHTML(html){
let txt = document.createElement('textarea');
txt.innerHTML = html;
return txt.value;
}
function resetQuiz(){
currentQuestionIndex = 0;
currentQuestionNumber = 1;
startquiz();
}
//rerendering html after restart
function clearHTML(){
question.textContent = '';
option1.nextElementSibling.textContent = '';
option2.nextElementSibling.textContent = '';
option3.nextElementSibling.textContent = '';
option4.nextElementSibling.textContent = '';
randomOptions = [];
error_msg.classList.add('hidden');
display_answer.classList.add('hidden');
userScore = 0;
}
nextBtn.addEventListener('click', nextQuestion);
previousBtn.addEventListener('click', previousQuestion);
beginBtn.addEventListener('click', startquiz);
restartBtn.addEventListener('click', resetQuiz);
displayCategory();