-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
52 lines (44 loc) · 1.27 KB
/
script.js
File metadata and controls
52 lines (44 loc) · 1.27 KB
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
const questionEl = document.querySelector("#question");
const nextBtn = document.querySelector("#next");
const restartBtn = document.querySelector("#restart");
const topic = document.querySelector("#topic");
function random() {
const l = currentQuestions.length;
const random = Math.floor(Math.random() * l);
const currentQuestion = currentQuestions.splice(random, 1)[0];
return currentQuestion;
}
let currentQuestions = [];
function showRandomQuestion() {
const currentQuestion = random();
if (currentQuestion !== undefined) {
questionEl.innerText = currentQuestion;
} else {
nextBtn.hidden = true;
restartBtn.hidden = false;
restartBtn.focus();
questionEl.innerText = "Done 🎉";
}
}
function restart() {
initQuizbox();
}
nextBtn.addEventListener("click", showRandomQuestion);
restartBtn.addEventListener("click", restart);
topic.addEventListener("change", initQuizbox);
function initQuizbox() {
nextBtn.hidden = false;
restartBtn.hidden = true;
nextBtn.focus();
const url = "questions/" + topic.value + ".json";
fetch(url)
.then((res) => res.json())
.then((data) => {
currentQuestions = data.questions;
showRandomQuestion();
})
.catch((err) => {
console.error("OH NO! Anyway", err);
});
}
initQuizbox();