forked from hasnain23233/QuizApp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
94 lines (84 loc) · 2.77 KB
/
script.js
File metadata and controls
94 lines (84 loc) · 2.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const API_URL = "https://opentdb.com/api.php?amount=3&type=multiple";
let questions = [];
let currentQuestion = 0;
let score = 0;
const questionElement = document.getElementById("question");
const optionsContainer = document.getElementById("options");
const nextButton = document.getElementById("next-btn");
const restartButton = document.getElementById("restart-btn");
const resultElement = document.getElementById("result");
const scoreElement = document.getElementById("score");
const totalQuestionsElement = document.getElementById("total-questions");
async function fetchQuestions() {
try {
const response = await fetch(API_URL);
const data = await response.json();
questions = data.results.map((q) => ({
question: q.question,
options: shuffleArray([...q.incorrect_answers, q.correct_answer]),
answer: q.correct_answer,
}));
totalQuestionsElement.textContent = questions.length;
loadQuestion();
} catch (error) {
alert("Failed to fetch questions from API!");
console.error(error);
}
}
function shuffleArray(array) {
return array.sort(() => Math.random() - 0.5);
}
function loadQuestion() {
const current = questions[currentQuestion];
questionElement.innerHTML = current.question;
optionsContainer.innerHTML = "";
current.options.forEach((option) => {
const label = document.createElement("label");
label.innerHTML = `
<input type="radio" name="option" value="${option}">
${option}
`;
optionsContainer.appendChild(label);
});
}
function getSelectedOption() {
const options = document.getElementsByName("option");
for (let option of options) {
if (option.checked) {
return option.value;
}
}
return null;
}
function showResult() {
resultElement.style.display = "block";
scoreElement.textContent = score;
nextButton.style.display = "none";
restartButton.style.display = "block";
}
nextButton.addEventListener("click", () => {
const selected = getSelectedOption();
if (!selected) {
alert("Please select an answer before proceeding!");
return;
}
if (selected === questions[currentQuestion].answer) {
score++;
}
currentQuestion++;
if (currentQuestion < questions.length) {
loadQuestion();
} else {
showResult();
}
});
restartButton.addEventListener("click", () => {
currentQuestion = 0;
score = 0;
resultElement.style.display = "none";
nextButton.style.display = "block";
restartButton.style.display = "none";
loadQuestion();
});
// Fetch and load questions on page load
fetchQuestions();