I’m developing a small JavaScript quiz to practice the language and add a project to my portfolio.
So far, I have successfully implemented randomized questions and choices, a timer, a progress bar and a score counter.
However, I have been experiencing issues with having my code recognise the fact when the user is submitting the option that should register as correct and light up green.
I would much appreciate any input in this regard.
I have tried to create a different const that targets the ‘answer’ property in my array of objects and have the code check if this matches the user input. However, this doesn’t seem to make a difference in the code.
Here’s the questions array;
let questions = [
{
question: 'According to Roman mythology, who was the father of Romulus and Remus?',
choice1: 'A wolf',
choice2: 'King Numitor',
choice3: 'Jupiter',
choice4: 'Mars',
answer: 4,
},
{
question: 'Which was the first Roman road?',
choice1: 'Via Egnatia',
choice2: 'Via Valeria',
choice3: 'Via Appia',
choice4: 'Via Flaminia',
answer: 3,
},
{
question: 'Which of the following did not defeat Mithridates VI of Pontus?',
choice1: 'Lucullus',
choice2: 'Marius',
choice3: 'Pompey',
choice4: 'Sulla',
answer: 2,
},
{
question: 'How many times was Rome sacked in antiquity?',
choice1: 'Once',
choice2: 'Three or four',
choice3: 'Six',
choice4: 'Twice',
answer: 2,
},
{
question: 'What is an ancient roman marketplace called?',
choice1: 'Agora',
choice2: 'Market',
choice3: 'Forum',
choice4: 'Centre',
answer: 3,
},
{
question: 'How many heirs did Augustus lose before his death on 19 August AD 14?',
choice1: 'Five',
choice2: 'Four',
choice3: 'Three',
choice4: 'Six',
answer: 1,
},
{
question: 'Which of the following did NOT die in battle in Mesopotamia?',
choice1: 'Gordian III',
choice2: 'Julius',
choice3: 'Crassus',
choice4: 'Valerian',
answer: 5,
},
{
question: 'Which of the following emperors did not win a victory against the Goths?',
choice1: 'Theodosius I',
choice2: 'Valens',
choice3: 'Julian',
choice4: 'Justinian',
answer: 3,
},
{
question: 'Between which forces was the Battle of Cannae fought?',
choice1: 'Epirus and Macedon',
choice2: 'Carthage and Rome',
choice3: 'Sparta and Arcadia',
choice4: 'Pergamon and Anatolia',
answer: 3,
},
]
Here’s the relevant logic;
choices.forEach(choice => {
choice.addEventListener('click', e => {
if(!acceptingAnswers) return
acceptingAnswers = false;
const selectedChoice = e.target;
const correctAnswer = questions.answer;
const selectedAnswer = selectedChoice.dataset['number'];
let classToApply = selectedAnswer == correctAnswer ? 'correct' : 'incorrect';
if(classToApply === 'correct') {
incrementScore(SCORE_POINTS);
}
selectedChoice.parentElement.classList.add(classToApply);
setTimeout(() => {
selectedChoice.parentElement.classList.remove(classToApply);
getNewQuestion();
}, 1000);
})
})
Thank you kindly for your time in advance and I’m looking forward to learning about how I can tackle this issue.