-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
73 lines (57 loc) · 2.31 KB
/
script.js
File metadata and controls
73 lines (57 loc) · 2.31 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
// script.js
// Make sure questions.js is loaded before this script
// You can include it in your HTML before this script tag
const questionElement = document.getElementById('question');
const optionsElement = document.getElementById('options');
const submitButton = document.getElementById('submit');
const resultElement = document.getElementById('result');
let currentQuestion = 0;
let score = 0;
function displayQuestion() {
questionElement.textContent = questions[currentQuestion].question;
optionsElement.innerHTML = '';
for (let i = 0; i < questions[currentQuestion].options.length; i++) {
const option = document.createElement('button');
option.textContent = questions[currentQuestion].options[i];
option.addEventListener('click', () => checkAnswer(i));
optionsElement.appendChild(option);
}
}
function checkAnswer(selectedIndex) {
questions[currentQuestion].userAnswerIndex = selectedIndex;
if (selectedIndex === questions[currentQuestion].correctAnswer) {
score++;
}
currentQuestion++;
if (currentQuestion < questions.length) {
displayQuestion();
} else {
showResult();
}
}
function showResult() {
questionElement.style.display = 'none';
optionsElement.style.display = 'none';
submitButton.style.display = 'none';
let resultHTML = `You scored ${score} out of ${questions.length}!<br><br>`;
resultHTML += '<strong>Questions and Answers:</strong><br><br>';
for (let i = 0; i < questions.length; i++) {
const userAnswer = questions[i].options[questions[i].userAnswerIndex];
const correctAnswer = questions[i].options[questions[i].correctAnswer];
resultHTML += `<p><strong>Question ${i + 1}:</strong> ${questions[i].question}</p>`;
resultHTML += `<p>Your Answer: ${userAnswer}</p>`;
resultHTML += `<p>Correct Answer: ${correctAnswer}</p><br>`;
}
resultElement.innerHTML = resultHTML;
}
// Load questions from external file and start the quiz
function loadQuestions() {
const script = document.createElement('script');
script.src = 'questions.js';
script.onload = () => {
displayQuestion();
};
document.body.appendChild(script);
}
// Start loading questions when the page is ready
document.addEventListener('DOMContentLoaded', loadQuestions);