-
Notifications
You must be signed in to change notification settings - Fork 18
/
script.js
66 lines (56 loc) 路 2.13 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
const correctAnswer = ["D", "B", "C", "B", "D", "A", "B", "D", "A", "B", "A", "C", "B", "C", "D", "C", "B", "C", "A", "C", "C","B","D", "B"];
const correctOptions = ["D", "B", "C", "B", "D", "A", "B", "D", "A", "B", "A", "C", "B", "C", "D", "C", "B", "C", "A", "C", "C","B","D", "B"];
const form = document.querySelector(".quiz-form");
const result = document.querySelector(".result");
const questions = document.querySelectorAll(".question");
const messageElement = document.getElementById("message");
form.addEventListener("submit", (event) => {
event.preventDefault();
let score = 0;
const userAnswers = [
...document.querySelectorAll("input[type=radio]:checked"),
].map((el) => el.value);
userAnswers.forEach((answer, index) => {
if (answer === correctAnswer[index]) {
score += 1;
questions[index].classList.add("correct");
} else {
questions[index].classList.add("wrong");
// Find the correct option and highlight it
const options = questions[index].querySelectorAll(".option");
options.forEach((option) => {
const optionValue = option.querySelector("input").value;
if (correctOptions[index] === optionValue) {
option.classList.add("correct-option");
}
});
}
});
scrollTo(0, 0);
result.classList.remove("hide");
result.querySelector(
"p"
).textContent = `You scored ${score}/${userAnswers.length}!`;
if (score === userAnswers.length) {
messageElement.textContent = "Excellent!";
} else if (score >= Math.floor(userAnswers.length * 0.7)) {
messageElement.textContent = "Good!";
} else if (score >= Math.floor(userAnswers.length * 0.5)) {
messageElement.textContent = "Average!";
} else {
messageElement.textContent = "Try Once more!";
}
});
let mybutton = document.getElementById("scrolltoTop");
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
mybutton.style.display = "block";
} else {
mybutton.style.display = "none";
}
}
function topFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}