-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
86 lines (72 loc) · 2.66 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
// script.js
const questions = [
{
question: "What is the capital of France?",
choices: ["Berlin", "Madrid", "Paris", "Lisbon"],
correctAnswer: 2,
},
{
question: "Which planet is known as the Red Planet?",
choices: ["Earth", "Mars", "Jupiter", "Saturn"],
correctAnswer: 1,
},
{
question: "What is the largest ocean on Earth?",
choices: ["Atlantic", "Indian", "Arctic", "Pacific"],
correctAnswer: 3,
},
];
let currentQuestionIndex = 0;
let score = 0;
function loadQuestion() {
const questionElement = document.getElementById("question");
const choicesContainer = document.getElementById("choices");
const feedback = document.getElementById("feedback");
feedback.innerText = "";
const currentQuestion = questions[currentQuestionIndex];
questionElement.innerText = currentQuestion.question;
choicesContainer.innerHTML = "";
currentQuestion.choices.forEach((choice, index) => {
const button = document.createElement("button");
button.innerText = choice;
button.onclick = () => checkAnswer(index);
choicesContainer.appendChild(button);
});
}
function checkAnswer(selectedIndex) {
const feedback = document.getElementById("feedback");
const currentQuestion = questions[currentQuestionIndex];
if (selectedIndex === currentQuestion.correctAnswer) {
score++;
feedback.innerText = "Correct!";
feedback.style.color = "green";
} else {
feedback.innerText = `Wrong! The correct answer was "${currentQuestion.choices[currentQuestion.correctAnswer]}".`;
feedback.style.color = "red";
}
document.getElementById("next-btn").style.display = "block";
}
function nextQuestion() {
currentQuestionIndex++;
if (currentQuestionIndex < questions.length) {
loadQuestion();
document.getElementById("next-btn").style.display = "none";
} else {
displayResult();
}
}
function displayResult() {
document.getElementById("quiz-container").style.display = "none";
document.getElementById("result-container").style.display = "block";
document.getElementById("score").innerText = `${score} / ${questions.length}`;
}
function restartQuiz() {
currentQuestionIndex = 0;
score = 0;
document.getElementById("quiz-container").style.display = "block";
document.getElementById("result-container").style.display = "none";
loadQuestion();
document.getElementById("next-btn").style.display = "none";
}
// Initialize quiz on page load
loadQuestion();