Skip to content
Advertisement

Can’t add an event listener to an element from an API

I am building a trivia webapp using an API and i want to add an event listener to the button with the correct answer so that when the user clicks it it will display a message saying they’re right and it’ll get a new question. Here’s how the code looks:

function useApiData(triviaObj) {
  let answers = sortArrayRandomly([
    triviaObj.results[0].correct_answer,
    triviaObj.results[0].incorrect_answers[0],
    triviaObj.results[0].incorrect_answers[1],
    triviaObj.results[0].incorrect_answers[2],
  ]);

  document.querySelector("#category").innerHTML = `Category: ${triviaObj.results[0].category}`;
  document.querySelector("#difficulty").innerHTML = `Difficulty: ${triviaObj.results[0].difficulty}`;
  document.querySelector("#question").innerHTML = `Question: ${triviaObj.results[0].question}`;

  document.querySelector("#answer1").innerHTML = `${answers[0]}`;
  document.querySelector("#answer2").innerHTML = `${answers[1]}`;
  document.querySelector("#answer3").innerHTML = `${answers[2]}`;
  document.querySelector("#answer4").innerHTML = `${answers[3]}`;

  let rightAnswer = triviaObj.results[0].correct_answer;
  rightAnswer.addEventListener("click", correctAnswer);

  console.log(answers);
}

function correctAnswer() {
  alert("correct");
  getTrivia();
}

It tells me that the AddEventListener is not a function, how can I fix this?

Advertisement

Answer

Use a loop to fill in the answer elements. In that loop you can check if the current answer is the correct answer and add the event listener.

answers.forEach((answer, i) => {
  let button = document.querySelector(`#answer${i+1}`);
  button.innerHTML = answer;
  if (answer == triviaObj.results[0].correct_answer) {
    button.addEventListener("click", correctAnswer);
  } else {
    button.removeEventListener("click", correctAnswer);
  }
});
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement