-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
322 lines (277 loc) · 8.54 KB
/
Copy pathscript.js
File metadata and controls
322 lines (277 loc) · 8.54 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
"use strict";
// Question bank: update or extend as you like
const questions = [
{
question: "Which language runs in a web browser?",
options: ["Java", "C", "Python", "JavaScript"],
answer: 3,
},
{
question: "What does CSS stand for?",
options: [
"Central Style Sheets",
"Cascading Style Sheets",
"Cascading Simple Sheets",
"Cars SUVs Sailboats",
],
answer: 1,
},
{
question: "What does HTML stand for?",
options: [
"Hypertext Markup Language",
"Hyperloop Machine Language",
"Hyperlink and Text Markup Language",
"Home Tool Markup Language",
],
answer: 0,
},
{
question: "What year was JavaScript launched?",
options: ["1996", "1995", "1994", "None of the above"],
answer: 1,
},
{
question: "Which one is NOT a programming language?",
options: ["Kotlin", "Swift", "Banana", "Go"],
answer: 2,
},
{
question: "Which array method creates a new array with results of a callback?",
options: ["forEach", "map", "filter", "reduce"],
answer: 1,
},
{
question: "Which CSS unit scales with the root font size?",
options: ["px", "em", "rem", "%"],
answer: 2,
},
];
// Active question set (shuffled each start)
let activeQuestions = [];
function shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
let currentIndex = 0;
let score = 0;
// Elements
// Login elements
const loginCard = document.getElementById("login-card");
const loginForm = document.getElementById("login-form");
const nameInput = document.getElementById("name");
const emailInput = document.getElementById("email");
const loginMessage = document.getElementById("login-message");
// Quiz elements
const quizCard = document.getElementById("quiz-card");
const resultCard = document.getElementById("result-card");
const questionEl = document.getElementById("question");
const answersEl = document.getElementById("answers");
const progressEl = document.getElementById("progress");
const nextBtn = document.getElementById("next-btn");
const finalScoreEl = document.getElementById("final-score");
const restartBtn = document.getElementById("restart-btn");
const timerEl = document.getElementById("timer");
// Timer state (2 minutes)
const QUIZ_DURATION_SECONDS = 120; // 2 minutes
let remainingSeconds = QUIZ_DURATION_SECONDS;
let timerId = null;
// Simple storage helpers
const STORAGE_KEY_USERS = "quiz_users_attempts_v1";
let usersAttempts = JSON.parse(localStorage.getItem(STORAGE_KEY_USERS) || "{}");
function saveAttempts() {
localStorage.setItem(STORAGE_KEY_USERS, JSON.stringify(usersAttempts));
}
function initQuiz() {
currentIndex = 0;
score = 0;
// Create a shuffled copy each start/refresh
activeQuestions = shuffle(questions.slice());
// Show quiz, hide result
resultCard.classList.remove("show");
resultCard.classList.add("hidden");
quizCard.classList.add("show");
quizCard.classList.remove("hidden");
// Reset and start timer
stopTimer();
remainingSeconds = QUIZ_DURATION_SECONDS;
updateTimerUI();
startTimer();
showQuestion();
}
function showQuestion() {
// Reset state
nextBtn.classList.add("hidden");
answersEl.innerHTML = "";
const q = activeQuestions[currentIndex];
questionEl.textContent = q.question;
progressEl.textContent = `Question ${currentIndex + 1} of ${activeQuestions.length}`;
// Render shuffled answer buttons
const shuffledAnswers = shuffle(
q.options.map((text, idx) => ({ text, isCorrect: idx === q.answer }))
);
shuffledAnswers.forEach(({ text, isCorrect }) => {
const btn = document.createElement("button");
btn.className = "btn option";
btn.type = "button";
btn.textContent = text;
btn.dataset.correct = isCorrect ? "true" : "false";
btn.addEventListener("click", onSelectAnswer, { once: true });
answersEl.appendChild(btn);
});
// trigger enter animation
quizCard.classList.remove("fade-in");
void quizCard.offsetWidth; // reflow to restart animation
quizCard.classList.add("fade-in");
}
function onSelectAnswer(e) {
const selectedBtn = e.currentTarget;
const isCorrect = selectedBtn.dataset.correct === "true";
const optionButtons = Array.from(answersEl.children);
// mark correctness
if (isCorrect) {
selectedBtn.classList.add("correct");
score++;
} else {
selectedBtn.classList.add("incorrect");
// highlight the correct one
const correctBtn = optionButtons.find((b) => b.dataset.correct === "true");
if (correctBtn) correctBtn.classList.add("correct");
}
// disable all options
optionButtons.forEach((btn) => {
btn.disabled = true;
});
// show Next
nextBtn.classList.remove("hidden");
}
nextBtn.addEventListener("click", () => {
currentIndex++;
if (currentIndex < activeQuestions.length) {
showQuestion();
} else {
showResult();
}
});
function showResult() {
stopTimer();
quizCard.classList.remove("show");
quizCard.classList.add("hidden");
resultCard.classList.add("show");
resultCard.classList.remove("hidden");
finalScoreEl.textContent = `You scored ${score} out of ${activeQuestions.length}`;
// Mark attempt for the logged-in user
const currentUserEmail = emailInput?.value?.trim().toLowerCase();
if (currentUserEmail) {
usersAttempts[currentUserEmail] = {
name: nameInput?.value?.trim() || "",
completedAt: new Date().toISOString(),
score,
total: activeQuestions.length,
};
saveAttempts();
}
// Stay on result screen (no auto-quit)
}
restartBtn.addEventListener("click", () => {
// Back to login; do not allow retake
resultCard.classList.remove("show");
resultCard.classList.add("hidden");
loginCard.classList.remove("hidden");
// Clear inputs so a different user can log in
nameInput.value = "";
emailInput.value = "";
loginMessage.textContent = "You have already completed the quiz.";
loginMessage.className = "message error";
});
// Timer helpers
function startTimer() {
if (timerId) return; // avoid duplicate timers
timerId = setInterval(() => {
remainingSeconds--;
updateTimerUI();
if (remainingSeconds <= 0) {
remainingSeconds = 0;
updateTimerUI();
showResult(); // auto-finish on timeout
}
}, 1000);
}
function stopTimer() {
if (timerId) {
clearInterval(timerId);
timerId = null;
}
}
function updateTimerUI() {
if (!timerEl) return;
const m = Math.floor(remainingSeconds / 60).toString().padStart(2, "0");
const s = (remainingSeconds % 60).toString().padStart(2, "0");
timerEl.textContent = `${m}:${s}`;
// visual hints as time runs out
timerEl.classList.toggle("warning", remainingSeconds <= 60 && remainingSeconds > 20);
timerEl.classList.toggle("danger", remainingSeconds <= 20);
}
// Start: show login first
function showLogin() {
loginCard.classList.remove("hidden");
}
// Handle login
loginForm.addEventListener("submit", (e) => {
e.preventDefault();
const name = nameInput.value.trim();
const email = emailInput.value.trim().toLowerCase();
loginMessage.textContent = "";
loginMessage.className = "message";
if (!name || !email || !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) {
loginMessage.textContent = "Please enter a valid name and email.";
loginMessage.classList.add("error");
return;
}
// Check if user already completed the quiz
const attempt = usersAttempts[email];
if (attempt) {
loginMessage.textContent = "You have already completed the quiz.";
loginMessage.classList.add("error");
return;
}
// Proceed to quiz
loginCard.classList.add("hidden");
initQuiz();
});
// Timer helpers
function startTimer() {
if (timerId) return; // avoid duplicate timers
timerId = setInterval(() => {
remainingSeconds--;
updateTimerUI();
if (remainingSeconds <= 0) {
remainingSeconds = 0;
updateTimerUI();
showResult(); // auto-finish on timeout
}
}, 1000);
}
function stopTimer() {
if (timerId) {
clearInterval(timerId);
timerId = null;
}
}
function updateTimerUI() {
if (!timerEl) return;
const m = Math.floor(remainingSeconds / 60).toString().padStart(2, "0");
const s = (remainingSeconds % 60).toString().padStart(2, "0");
timerEl.textContent = `${m}:${s}`;
// visual hints as time runs out
timerEl.classList.toggle("warning", remainingSeconds <= 60 && remainingSeconds > 20);
timerEl.classList.toggle("danger", remainingSeconds <= 20);
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", showLogin);
} else {
showLogin();
}