lundi 22 mars 2021

Why is the click event triggered multiple times after just one click?

I would really appreciate some help with this code I have been stuck on for a while.

My aim with this is to create a feedback for clicking an answer (multiple choice) for a simple quiz question and then it calls the function apiQuestion() to move on to the next question.

How I have attempted this is by adding an if else statement where the condition compares the clicked answer with the correct answer data inside a click event listener. It is within the scope of a fetch promise.

The problem is that after the first initial click, the click event is increasingly repeated for every subsequent event.

Again, I would greatly appreciate the help!

function apiQuestion() {
    fetch(`https://opentdb.com/api.php?amount=39&category=31&type=multiple`)
    .then(res => res.json())
    .then(rawData => {
        let quizData = shuffle(rawData.results);
        let question = quizData[0].question;
        let correctAnswer = quizData[0].correct_answer;
        let incorrectAnswers = quizData[0].incorrect_answers;

        quizQuestion.innerHTML = question;

        answers.forEach(answer => {
            answer.innerHTML = incorrectAnswers.shift() || correctAnswer;
        });

        console.log("Correct answer: " + correctAnswer);

        answers.forEach(answer => {
            answer.addEventListener('click', clickFeedback = (e) => {
                answer.removeEventListener('click', clickFeedback)
                let clickedItem = e.target.innerHTML;
                if (clickedItem == correctAnswer) {
                    console.log("CORRECT!");
                } else {
                    console.log("INCORRECT!");
                }
                apiQuestion();
                return;
            })
        });
    })
    .catch((err) => {
        console.error(err);
    });
};

Aucun commentaire:

Enregistrer un commentaire