-
Notifications
You must be signed in to change notification settings - Fork 2
/
fireApp.js
452 lines (399 loc) · 13.7 KB
/
fireApp.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
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
const result = document.getElementById('result-container')
const questionContainer = document.getElementById('question-container')
const form = document.getElementById('quiz-form')
const sliderLabel = document.querySelector('#slidertext')
const progressContainers = document.getElementsByClassName('progress-container')
const resultLink = document.getElementById('studentListLink')
const dropmenu = document.getElementById('dropid')
const quizlink = document.getElementById('quizlink')
import { initializeApp } from 'https://www.gstatic.com/firebasejs/10.4.0/firebase-app.js'
import {
getFirestore,
collection,
addDoc,
getDocs,
getDoc,
where,
query,
} from 'https://www.gstatic.com/firebasejs/10.4.0/firebase-firestore.js'
// Your web app's Firebase configuration
import firebaseConfig from './firebaseConfig.js'
// Initialize Firebase
const app = initializeApp(firebaseConfig)
const db = getFirestore(app)
//Retrive Function
async function getFireBaseJSON(lang, level) {
const querySnapshot = await getDocs(
query(
collection(db, 'questions'),
where('questionData.lang', '==', lang),
where('questionData.level', '==', level)
)
)
return querySnapshot
}
let quizData
let importData = []
let currentQuestionIndex = 0
let correct, wrong, userlength
let timeout = false
// Add an event listener to the checkbox
let timer = true
const quizSlider = document.getElementById('quiz-slider').checked
if (quizSlider) {
sliderLabel.textContent = 'On'
console.log(sliderLabel.textContent)
sliderLabel.classList.add('slider-label-on')
}
document.getElementById('quiz-slider').addEventListener('change', function () {
if (this.checked) {
timer = true
sliderLabel.textContent = 'On'
sliderLabel.classList.remove('slider-label-off')
sliderLabel.classList.add('slider-label-on')
console.log('Timer ' + timer)
} else {
timer = false
console.log('Timer ' + timer)
sliderLabel.textContent = 'Off'
sliderLabel.classList.remove('slider-label-on')
sliderLabel.classList.add('slider-label-off')
}
// console.log('Slider ' + quizSlider)
})
function shuffleArray(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]]
}
}
async function loadQuizData(language, difficulty) {
try {
const data = await getFireBaseJSON(language, difficulty)
console.log('Data Loaded')
console.log(data)
data.forEach((doc) => {
const JSONData = doc.data().questionData
importData.push(JSONData)
})
if (importData.length === 0) {
dispFeedback(`Questions not found for ${language}`, 'error')
setTimeout(function () {
location.reload()
}, 2000) // 4000 milliseconds = 4 seconds
}
//Filter By Difficulty Level
quizData = importData
//Define length
if (userlength > quizData.length) {
userlength = quizData.length
}
console.log('Length ' + userlength)
shuffleArray(quizData)
//Display First Que
displayQuestion(currentQuestionIndex)
} catch (error) {
console.error('Error loading quiz data:', error)
}
}
function startQuiz() {
const language = document.getElementById('language').value
const difficulty = document.getElementById('difficulty').value
userlength = document.getElementById('quiz-type').value
console.log('Lan : ' + language)
correct = 0
wrong = 0
if (language === 'none' || difficulty === 'none') {
alert('Please select a language and difficulty level.')
return
}
loadQuizData(language, difficulty)
document.getElementById('quiz-form').style.display = 'none'
}
function displayQuestion(questionIndex) {
timeout = false
questionContainer.style.display = 'block'
const question = quizData[questionIndex]
const shuffledOptions = [...question.options]
console.log('Options ')
console.log(shuffledOptions)
console.log('Ans ')
console.log(quizData[questionIndex].ans)
shuffleArray(shuffledOptions)
if (!question) {
endQuiz()
return
}
const questionHTML = `
<div class="progress-container">
<div class="progress-bar" id="progress-bar"></div>
</div>
<h5>${question.question}</h5>
<ul>
${shuffledOptions
.map(
(option, index) => `
<div class="option">
<input type="radio" name="answer" value="${index}" id="option${index}" />
<label for="option${index}">${option}</label>
</div>
`
)
.join('')}
</div>
</ul>
<div id="feedback-container" class="feedback"></div>
<div class="btncontainer">
<button type="button" id="btn">Submit</button>
<button type="button" id="btn2">Next Quiz</button>
<button type="button" id="btn3">Exit</button>
</div>
<div id="popup" class="popup">
<div class="popup-content">
<span class="close-button" id="closePopup">×</span>
<h2>Quiz Exit Confirmation</h2>
<p>If you exit, any unsaved progress will be lost.</p>
<button id="reloadPage">Exit Quiz</button>
</div>
</div>
`
questionContainer.innerHTML = questionHTML
console.log('Timer ' + timer)
setTimeout(function () {
window.scrollTo({
top: document.body.scrollHeight,
behavior: 'smooth',
})
}, 100) // Adjust the delay (in milliseconds) as needed
document.getElementById('popup').style.display = 'none'
document.getElementById('btn3').addEventListener('click', function () {
document.getElementById('popup').style.display = 'flex'
})
// Get all option divs
const optionDivs = document.querySelectorAll('.option')
// Add a click event listener to each option div
optionDivs.forEach((optionDiv) => {
optionDiv.addEventListener('click', () => {
// Check the corresponding radio button
const radioButton = optionDiv.querySelector('input[type="radio"]')
radioButton.checked = true
})
})
document.getElementById('closePopup').addEventListener('click', function () {
document.getElementById('popup').style.display = 'none'
})
document.getElementById('reloadPage').addEventListener('click', function () {
location.reload()
})
if (!timer) {
for (const container of progressContainers) {
container.style.display = 'none'
}
} else {
for (const container of progressContainers) {
container.style.display = 'block'
}
console.log('Progress Start')
startProgressBar()
}
currentQuestionIndex = questionIndex
const submitButton = document.getElementById('btn')
submitButton.addEventListener('click', function () {
checkAnswer(currentQuestionIndex)
})
const nextButton = document.getElementById('btn2')
nextButton.addEventListener('click', function () {
displayNextQuestion(currentQuestionIndex)
})
}
function disableQuizOptions() {
const optionContainers = document.querySelectorAll('.option')
optionContainers.forEach(function (container) {
const input = container.querySelector('input[type="radio"]')
input.disabled = true
// Optionally, you can add a class to visually indicate that the option is disabled
container.classList.add('disabled-option')
})
}
function startProgressBar() {
const progressBar = document.getElementById('progress-bar')
progressBar.style.width = '0%' // Initially set to 0%
let submitButtonClicked = false // Flag to check if the "Next" button was clicked
const animationDuration = 10000 // 10 seconds
const animationSteps = 400
const stepWidth = 50 / animationSteps
let currentWidth = 0
const animationInterval = animationDuration / animationSteps
const animation = setInterval(function () {
currentWidth += stepWidth
progressBar.style.width = currentWidth + '%'
if (currentWidth >= 100) {
clearInterval(animation)
if (!submitButtonClicked) {
console.log('Next')
// If the "Next" button was not clicked, move to the next question
timeout = true
displayFeedback('Time Out', 'error')
checkAnswer(currentQuestionIndex)
}
}
}, animationInterval)
const submitButton = document.getElementById('btn')
submitButton.addEventListener('click', function () {
submitButtonClicked = true
clearInterval(animation) // Stop the animation if the "Next" button is clicked
})
}
// Function to reset the progress bar
// function resetProgressBar() {
// progressBar.style.width = '0'
// }
// Example: Start the progress bar for each quiz question
// You can call startProgressBar() for each question in your quiz.
function displayFeedback(message, className) {
const feedbackContainer = document.getElementById('feedback-container')
feedbackContainer.textContent = message
feedbackContainer.classList.add('feedback', className)
feedbackContainer.style.display = 'block'
}
function dispFeedback(message, className) {
const feedbackContainer = document.getElementById('feedback-cont')
feedbackContainer.textContent = message
feedbackContainer.classList.add('feedback', className)
feedbackContainer.style.display = 'block'
}
function checkAnswer(questionIndex) {
console.log('Check')
const progressBar = document.getElementById('progress-bar')
progressBar.style.width = '100%'
let selectedAnswerText
progressBar.style.width = '0%' // Initially set to 0%
const selectedRadioButton = document.querySelector(
'input[name="answer"]:checked'
)
if (selectedRadioButton) {
selectedAnswerText = selectedRadioButton.nextElementSibling.textContent
// Now you can use the selectedAnswerText
console.log(selectedAnswerText)
} else {
// Handle the case where no option is selected
console.log('Please select an option.')
}
if (!selectedAnswerText && timeout == false) {
console.log(selectedAnswerText)
alert('Please select an answer')
return
} else {
console.log('Option selected')
}
const selectedAnswerElement = document.querySelector(
'input[name="answer"]:checked + label'
)
// Now selectedAnswerText will contain the text of the selected option.
console.log(!selectedAnswerText && selectedAnswerText)
const correctAnswerText = quizData[questionIndex].ans
const correctAnswerOption = quizData[questionIndex].options.find(
(option) => option.correct
)
document.getElementById('btn2').style.display = 'block'
document.getElementById('btn').style.display = 'none'
if (timeout == true) {
disableQuizOptions()
wrong++
console.log('Time Out, selected, not submitted ')
const allLabels = document.querySelectorAll('label')
for (const label of allLabels) {
if (label.textContent === correctAnswerText) {
label.classList.add('correct')
break // Stop searching after finding the correct label
}
}
} else if (!selectedAnswerText) {
alert('Please select an answer.')
return
} else {
if (selectedAnswerText === correctAnswerText && timeout == false) {
disableQuizOptions()
console.log('In Time, selected, submitted ')
correct++
selectedAnswerElement.classList.add('correct')
// displayFeedback('Correct answer!', 'green')
} else {
disableQuizOptions()
wrong++
selectedAnswerElement.classList.add('incorrect')
const allLabels = document.querySelectorAll('label')
for (const label of allLabels) {
if (label.textContent === correctAnswerText) {
label.classList.add('correct')
break // Stop searching after finding the correct label
}
}
}
}
}
function displayNextQuestion() {
document.getElementById('btn').style.display = 'block'
document.getElementById('btn2').style.display = 'none'
if (currentQuestionIndex < userlength - 1) {
displayQuestion(currentQuestionIndex + 1)
} else {
document.getElementById('question-container').style.display = 'none'
result.style.display = 'block'
win()
const innerHTML = `
<h2>Quiz completed!</h2>
<h3>Score : ${correct} / ${correct + wrong} </h3>
<h3 id="res">Correct : ${correct}</h3>
<h3 id="res">Wrong : ${wrong}</h3>
<button type="button" class="btncss" id="startagain">Start Again</button>
`
result.innerHTML = innerHTML
const uname = document.getElementById('name').value
window.addToFireBase(uname, correct, correct, wrong)
const startagain = document.getElementById('startagain')
startagain.addEventListener('click', function () {
startAgain()
})
// alert('No more questions.')
}
}
function startAgain() {
console.log('Data in startAgain : ')
console.log(importData)
console.log(quizData)
importData = []
quizData = importData
console.log('Remove')
console.log(importData)
console.log(quizData)
currentQuestionIndex = 0
form.reset()
result.style.display = 'none'
form.style.display = 'block'
resultLink.classList.remove('disable-link')
quizlink.classList.remove('disable-link')
dropmenu.classList.remove('disable-link')
// Enable the checkbox
document.getElementById('quiz-slider').removeAttribute('disabled')
document.getElementById('feedback-cont').style.display = 'none'
}
function endQuiz() {
const questionContainer = document.getElementById('question-container')
questionContainer.innerHTML = '<h2>Quiz completed!</h2>'
}
document.getElementById('quiz-form').addEventListener('submit', function (e) {
e.preventDefault()
// document.getElementById('popup').style.display = 'none'
document.getElementById('quiz-slider').setAttribute('disabled', 'disabled')
resultLink.classList.add('disable-link')
quizlink.classList.add('disable-link')
dropmenu.classList.add('disable-link')
startQuiz()
setTimeout(function () {
window.scrollTo({
top: document.body.scrollHeight,
behavior: 'smooth',
})
}, 100) // Adjust the delay (in milliseconds) as needed
})