Home > Enterprise >  Correct answer button green
Correct answer button green

Time:02-14

I am creating a quiz, and I am trying to turn my answer button green when correct and when incorrect red and then save this information and move onto the next question. However the code at the moment is not working. This is my JavaScript code:

let shuffledQuestions, currentQuestionIndex;

const setNextQuestion = () => {
    showQuestion(shuffledQuestions[currentQuestionIndex]);
}

const showQuestion = (gameData) => {
    questionElement.innerText = gameData.question;
    let answersBlock = '';
    gameData.answer.forEach((answer, index) => {
        const answerButton = `
            <div >
                <button  id="answersbutton-${index   1}" onclick="selectAnswer()">
                    ${answer.text}
                </button>
            </div>
        `;
        answersBlock  = answerButton;
    });
    answerButtonsElement.innerHTML = answersBlock;
}

const selectAnswer = (e) => {
    const selectedButton = e.target;
    const correct = selectedButton.dataset.correct;
    setStatusClass(document.body, correct);
    Array.from(answerButtonsElement.children).forEach(button => {
        setStatusClass(button, button.dataset.correct);
    })
}

function setStatusClass(element, correct) {
    clearStatusClass(element);
    if (correct) {
        element.classList.add('correct');
    } else {
        element.classList.add('wrong');
    }
}

function clearStatusClass(element) {
    element.classList.remove('correct');
    element.classList.remove('wrong');
}


const gameData = [
    {
        question: 'What is the smallest country in the world?',
        answer: [
            { text: 'Vatican City', correct: true },
            { text: 'Malta', correct: false },
            { text: 'Italy', correct: false },
            { text: 'Monaco', correct: false }
        ]
    },

CodePudding user response:

You must pass the event as a parameter in onclick because you are using the event in HTML and calling it directly.

const answerButton = `
            <div >
                <button  id="answersbutton-${index   1}" onclick="selectAnswer(event)">
                    ${answer.text}
                </button>
            </div>
        `;

And get it as event.target in selectAnswer function.

function selectAnswer(event) {
  console.log("Button", event.target)
}
  • Related