diff --git a/index.html b/index.html index 534cd886..a5fee0b6 100644 --- a/index.html +++ b/index.html @@ -39,7 +39,7 @@

JavaScript Quiz

- + diff --git a/src/index.js b/src/index.js index 03737ba3..b1dc9897 100644 --- a/src/index.js +++ b/src/index.js @@ -32,7 +32,7 @@ document.addEventListener("DOMContentLoaded", () => { new Question("What is the mass–energy equivalence equation?", ["E = mc^2", "E = m*c^2", "E = m*c^3", "E = m*c"], "E = mc^2", 3), // Add more questions here ]; - const quizDuration = 120; // 120 seconds (2 minutes) + const quizDuration = 5; // 120 seconds (2 minutes) /************ QUIZ INSTANCE ************/ @@ -43,7 +43,7 @@ document.addEventListener("DOMContentLoaded", () => { quiz.shuffleQuestions(); - /************ SHOW INITIAL CONTENT ************/ + /************ SHOW INITIAL CONTENT ***********/ // Convert the time remaining in seconds to minutes and seconds, and pad the numbers with zeros if needed const minutes = Math.floor(quiz.timeRemaining / 60).toString().padStart(2, "0"); @@ -52,30 +52,49 @@ document.addEventListener("DOMContentLoaded", () => { // Display the time remaining in the time remaining container const timeRemainingContainer = document.getElementById("timeRemaining"); timeRemainingContainer.innerText = `${minutes}:${seconds}`; - - // Show first question - showQuestion(); - - + + showQuestion() /************ TIMER ************/ - let timer; - + function startCountdown() { + setInterval(() => { + quiz.timeRemaining--; + const minutes = Math.floor(quiz.timeRemaining / 60).toString().padStart(2, "0"); + const seconds = (quiz.timeRemaining % 60).toString().padStart(2, "0"); + timeRemainingContainer.innerText = `${minutes}:${seconds}`; + if (quiz.timeRemaining === 0) { + console.log('Time is up!'); + clearInterval(timer); + showResults(); + } + }, 1000 ) + } +startCountdown(); + +function restartQuiz() { + const restartButton = document.getElementById('restartButton'); + restartButton.addEventListener('click', () => { + quiz.currentQuestionIndex = 0; + quiz.correctAnswers = 0; + quiz.shuffleQuestions(); + quiz.timeRemaining = quizDuration; + showQuestion(); + startCountdown(); + quizView.style.display = 'block'; + endView.style.display = 'none'; + }) +} +restartQuiz() ; /************ EVENT LISTENERS ************/ - nextButton.addEventListener("click", nextButtonHandler); - - /************ FUNCTIONS ************/ // showQuestion() - Displays the current question and its choices // nextButtonHandler() - Handles the click on the next button // showResults() - Displays the end view and the quiz results - - function showQuestion() { // If the quiz has ended, show the results if (quiz.hasEnded()) { @@ -91,28 +110,22 @@ document.addEventListener("DOMContentLoaded", () => { const question = quiz.getQuestion(); // Shuffle the choices of the current question by calling the method 'shuffleChoices()' on the question object question.shuffleChoices(); - - - + // YOUR CODE HERE: - // // 1. Show the question // Update the inner text of the question container element and show the question text + questionContainer.innerText = question.text; // 2. Update the green progress bar // Update the green progress bar (div#progressBar) width so that it shows the percentage of questions answered - progressBar.style.width = `65%`; // This value is hardcoded as a placeholder - - + progressBar.style.width = `${(quiz.currentQuestionIndex / quiz.questions.length) * 100}%`; // This value is hardcoded as a placeholder // 3. Update the question count text // Update the question count (div#questionCount) show the current question out of total questions - questionCount.innerText = `Question 1 of 10`; // This value is hardcoded as a placeholder - - + questionCount.innerText = `Question ${quiz.currentQuestionIndex + 1} of ${quiz.questions.length}`; // This value is hardcoded as a placeholder // 4. Create and display new radio input element with a label for each choice. // Loop through the current question `choices`. @@ -128,39 +141,55 @@ document.addEventListener("DOMContentLoaded", () => { // Hint 3: You can use the `element.appendChild()` method to append an element to the choices container. // Hint 4: You can use the `element.innerText` property to set the inner text of an element. + console.log(question); + + question.choices.forEach((choice) => { + const inputEl = document.createElement('input'); + inputEl.type = 'radio'; + inputEl.name = 'choice'; + inputEl.value = choice; + const labelEl = document.createElement('label'); + labelEl.innerText = choice; + const newLine = document.createElement('br'); + choiceContainer.appendChild(inputEl); + choiceContainer.appendChild(labelEl); + choiceContainer.appendChild(newLine); + }) } - - - function nextButtonHandler () { - let selectedAnswer; // A variable to store the selected answer value - + let selectedAnswer; - - // YOUR CODE HERE: - // // 1. Get all the choice elements. You can use the `document.querySelectorAll()` method. - + const choices = document.querySelectorAll('input[type="radio"]'); // 2. Loop through all the choice elements and check which one is selected // Hint: Radio input elements have a property `.checked` (e.g., `element.checked`). // When a radio input gets selected the `.checked` property will be set to true. // You can use check which choice was selected by checking if the `.checked` property is true. - - + // 3. If an answer is selected (`selectedAnswer`), check if it is correct and move to the next question // Check if selected answer is correct by calling the quiz method `checkAnswer()` with the selected answer. // Move to the next question by calling the quiz method `moveToNextQuestion()`. // Show the next question by calling the function `showQuestion()`. - } - - + choices.forEach(choice => { + if (choice.checked) { + selectedAnswer = choice.value; + } + }); + if (!selectedAnswer) { + alert('Please select an answer before proceeding.'); + return; + } + if (selectedAnswer === quiz.questions[quiz.currentQuestionIndex].answer) { + quiz.correctAnswers++; + } + quiz.currentQuestionIndex++; + showQuestion(); + } function showResults() { - // YOUR CODE HERE: - // // 1. Hide the quiz view (div#quizView) quizView.style.display = "none"; @@ -168,7 +197,6 @@ document.addEventListener("DOMContentLoaded", () => { endView.style.display = "flex"; // 3. Update the result container (div#result) inner text to show the number of correct answers out of total questions - resultContainer.innerText = `You scored 1 out of 1 correct answers!`; // This value is hardcoded as a placeholder + resultContainer.innerText = `You scored ${quiz.correctAnswers} out of ${quiz.questions.length} correct answers!`; // This value is hardcoded as a placeholder } - }); \ No newline at end of file diff --git a/src/question.js b/src/question.js index 68f6631a..c8339215 100644 --- a/src/question.js +++ b/src/question.js @@ -1,7 +1,17 @@ class Question { - // YOUR CODE HERE: - // - // 1. constructor (text, choices, answer, difficulty) + constructor (text, choices, answer, difficulty) { + this.text = text; + this.choices = choices; + this.answer = answer; + this.difficulty = difficulty; + } + + shuffleChoices() { + for (let i = this.choices.length - 1; i > 0; i--){ + let j = Math.floor(Math.random() * (i + 1)); + [this.choices[i], this.choices[j]] = [this.choices[j], this.choices[i]]; + } + return this.shuffleChoices; + } +} - // 2. shuffleChoices() -} \ No newline at end of file diff --git a/src/quiz.js b/src/quiz.js index d94cfd14..920d1c47 100644 --- a/src/quiz.js +++ b/src/quiz.js @@ -1,15 +1,58 @@ class Quiz { - // YOUR CODE HERE: - // - // 1. constructor (questions, timeLimit, timeRemaining) + constructor(questions, timeLimit, timeRemaining) { + this.questions = questions; + this.timeLimit = timeLimit; + this.timeRemaining = timeRemaining; + this.correctAnswers = 0; + this.currentQuestionIndex = 0; + } - // 2. getQuestion() - - // 3. moveToNextQuestion() + getQuestion() { + return this.questions[this.currentQuestionIndex]; + } - // 4. shuffleQuestions() + moveToNextQuestion() { + this.currentQuestionIndex++; + } - // 5. checkAnswer(answer) + shuffleQuestions() { + for (let i = this.questions.length - 1; i > 0; i--) { + let j = Math.floor(Math.random() * (i + 1)); + [this.questions[i], this.questions[j]] = [ + this.questions[j], + this.questions[i], + ]; + } + return this.shuffleQuestions; + } - // 6. hasEnded() -} \ No newline at end of file + checkAnswer(answer) { + if (answer) { + this.correctAnswers++; + } + } + hasEnded() { + if (this.currentQuestionIndex < this.questions.length) { + return false; + } else if (this.currentQuestionIndex === this.questions.length) { + return true; + } + } + filterQuestionsByDifficulty(difficulty) { + if (typeof difficulty !== "number" || difficulty < 1 || difficulty > 3) { + return; + } + this.questions = this.questions.filter( + (question) => question.difficulty === difficulty + ); + } + averageDifficulty() { + if (this.questions.length === 0) + return 0; + const totalDifficulty = this.questions.reduce( + (sum, question) => sum + question.difficulty, + 0 + ); + return totalDifficulty / this.questions.length; + } +}