-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
72 lines (62 loc) · 1.77 KB
/
script.js
File metadata and controls
72 lines (62 loc) · 1.77 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
let questions = [];
let currentQuestion = 0;
let score = 0;
const questionEl = document.getElementById("question");
const optionsEl = document.getElementById("options");
const nextBtn = document.getElementById("nextBtn");
const resultEl = document.getElementById("result");
async function fetchQuestions() {
const res = await fetch("https://opentdb.com/api.php?amount=20&type=multiple");
const data = await res.json();
questions = data.results.map(q => ({
question: decodeHTMLEntities(q.question),
options: shuffle([q.correct_answer, ...q.incorrect_answers]),
answer: decodeHTMLEntities(q.correct_answer)
}));
loadQuestion();
}
function decodeHTMLEntities(str) {
const txt = document.createElement("textarea");
txt.innerHTML = str;
return txt.value;
}
function shuffle(array) {
return array.sort(() => Math.random() - 0.5);
}
function loadQuestion() {
const current = questions[currentQuestion];
questionEl.textContent = current.question;
optionsEl.innerHTML = "";
current.options.forEach(option => {
const li = document.createElement("li");
li.textContent = option;
li.onclick = () => selectAnswer(option);
optionsEl.appendChild(li);
});
}
function selectAnswer(selected) {
if (selected === questions[currentQuestion].answer) {
score++;
}
currentQuestion++;
if (currentQuestion < questions.length) {
loadQuestion();
} else {
showResult();
}
}
function showResult() {
questionEl.style.display = "none";
optionsEl.style.display = "none";
nextBtn.style.display = "none";
resultEl.textContent = `You scored ${score} out of ${questions.length}!`;
}
nextBtn.onclick = () => {
currentQuestion++;
if (currentQuestion < questions.length) {
loadQuestion();
} else {
showResult();
}
};
fetchQuestions();