Created
April 13, 2025 16:26
-
-
Save davidystephenson/90de25f646eef94cbceef1ab1dba6583 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let currentQuestion = 0 | |
let score = 0 | |
const numOfQuestions = questions.length | |
const numOfChoices = 3 | |
const questionCountElement = document.getElementById('question-count') | |
const questionContainerElement = document.getElementById('question-container') | |
const choicesContainerElement = document.getElementById('choices-container') | |
function displayQuestion () { | |
const question = questions[currentQuestion] | |
console.log('question', question) | |
const questionElement = document.getElementById('question') | |
questionElement.innerText = question.question | |
const countMessage = `${currentQuestion + 1}/${numOfQuestions}` | |
questionCountElement.innerText = countMessage | |
const choices = document.getElementsByClassName('choice') | |
console.log('choices', choices) | |
// choices[0].innerText = question.choices[0] | |
// choices[1].innerText = question.choices[1] | |
// choices[2].innerText = question.choices[2] | |
const choicesArray = [...choices] | |
choicesArray.forEach((choice, index) => { | |
choice.innerText = question.choices[index] | |
}) | |
} | |
function checkAnswer (questionIndex) { | |
const question = questions[currentQuestion] | |
const correct = questionIndex === question.correctAnswer | |
if (correct) { | |
score += 1 // score++ | |
updateScore() | |
} | |
const more = currentQuestion < questions.length - 1 | |
if (more) { | |
currentQuestion += 1 | |
displayQuestion() | |
} else { | |
endQuiz() | |
} | |
} | |
function updateScore () { | |
const scoreElement = document.getElementById('score') | |
const last = currentQuestion === questions.length - 1 | |
if (last) { | |
const scoreMessage = `Final Score: ${score}/${questions.length}` | |
scoreElement.innerText = scoreMessage | |
} else { | |
const scoreMessage = `Current Score: ${score}` | |
scoreElement.innerText = scoreMessage | |
} | |
} | |
function endQuiz () { | |
questionCountElement.innerHTML = 'The quiz has been completed' | |
questionContainerElement.innerHTML = '' | |
choicesContainerElement.innerHTML = '' | |
} | |
function restartQuiz () { | |
currentQuestion = 0 | |
score = 0 | |
updateScore() | |
questionContainerElement.innerHTML = '<p id="question"></p>' | |
choicesContainerElement.innerHTML = ` | |
<button class="choice" onclick="checkAnswer(0)"></button> | |
<button class="choice" onclick="checkAnswer(1)"></button> | |
<button class="choice" onclick="checkAnswer(2)"></button> | |
` | |
displayQuestion() | |
} | |
displayQuestion() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment