-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquiz.js
More file actions
94 lines (71 loc) · 2.04 KB
/
Copy pathquiz.js
File metadata and controls
94 lines (71 loc) · 2.04 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
// GET HTML ELEMENT IN JAVASCRIPT
let div = document.querySelector('.question')
let nextBtn = document.querySelector('#nextBtn')
let ul = document.querySelector('.main-ul')
let index = 0
let result = 0
let totalMarks = 100
let questions = [] // Initialize an empty array to store the questions
// SUFFLE ARRAY
function shuffleArray(arr) {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
// RENDER ITEM ON QUIZ.HTML
let renderQuestion = (arr) => {
div.innerHTML = ''
let answer = [
...arr[index].incorrectAnswers, arr[index].correctAnswer
]
// console.log(answer);
div.innerHTML += `
<h3>Q${index + 1}: ${arr[index].question.text}</h3>
`;
ul.innerHTML = `
${shuffleArray(answer).map(
(items) => `
<li>
<input type="radio" name="choice" class="choice" id=${items} value=${items}><label for=${items}>${items}</label>
</li>`
)}
`
}
// NEXT BUTTON
nextBtn.addEventListener("click", () => {
const choice = document.querySelectorAll(".choice");
div.innerHTML = "";
choice.forEach((item) => {
if (item.checked) {
if (item.nextSibling.innerHTML === questions[index].correctAnswer) {
result += 10;
}
}
});
if (index < questions.length - 1) {
index += 1
renderQuestion(questions)
} else {
alert('Go to Result')
window.location = 'result.html'
localStorage.setItem(
"result",
JSON.stringify({
totalMarks,
result,
})
)
}
})
// API CALL DATA
axios("https://the-trivia-api.com/v2/questions")
.then(response => {
questions = response.data // Store the fetched questions in the questions array
renderQuestion(questions) // Render the first question
console.log(response);
})
.catch(error => {
console.log(error);
})