Unable to attach an event listener to an element fetched from an API

I'm currently in the process of developing a trivia web application using an API, and my goal is to incorporate an event listener onto the button which corresponds to the correct answer. This way, when users click on it, a message will appear confirming their correctness and prompting a new question to be displayed. Below is a snippet of the code I am working with:

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!"); //changed alert message for clarity
  getTrivia();
}

I encountered an issue indicating that AddEventListener is not recognized as a function. How can I resolve this problem?

Answer №1

Utilize a looping mechanism to populate the answer elements. Within this loop, you can validate if the current answer is correct and then attach the event listener accordingly.

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);
  }
}

Answer №2

Event listeners should be attached to DOM elements, not data variables. Locate the correct answer element and link the event listener there:

const correctAnswer = quizObj.questions[0].correct_answer;
const chosenAnswer = options.find((item) => item === correctAnswer);
const correctElement = Array.from(document.querySelectorAll('*[id^="option"]'))
  .find((element) => element.innerText.includes(correctAnswer))
correctElement.addEventListener("click", handleCorrectAnswer);

Answer №3

Let's say that

triviaObj.results[0].correct_answer
is a numerical representation of the correct answer, in that case:

Switch out

let rightAnswer = triviaObj.results[0].correct_answer;

for

let rightAnswer = document.querySelector(`#answer${triviaObj.results[0].correct_answer}`);

This alternative approach is much simpler compared to Zan Anger's method.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Post-render for HTML linkage

Is there a method to execute customized code after Knockout has inserted the html into the DOM and completed rendering? This is required in order to bind a nested view model to dynamically generated html code. Perhaps like this: <div data-bind="html: ...

Ways to access information received from AngularJS in a different Javascript file

I am currently using Angular to retrieve output from a controller and display it using ng-bind. However, I have another separate JavaScript file that needs to utilize a value returned from Angular. In the example code provided below, the TestAppCtrl is ca ...

Obtaining a cookie in Vue.js independently: a step-by-step guide

After setting a cookie using laravel, I'm looking to retrieve it in vue.js without relying on or installing any external dependencies. Can anyone please suggest a way to achieve this without extra tools? Your guidance would be greatly appreciated! ...

Creating Styles in Material-UI using makeStyles: Tips for Styling by Element Name

I am currently facing a challenge of adding a rule for all <p> tags within the current component. Despite searching through various sources such as material-ui documentation and Stack Overflow, I have been unable to find any information on how to add ...

Step-by-step Guide to Setting pageProps Property in Next.js Pages

When looking at the code snippet provided in .../pages/_app.js, the Component refers to the component that is being exported from the current page. For instance, if you were to visit , the exported component in .../pages/about.js would be assigned as the ...

The document.ready function does not seem to be functioning properly within an iframe

In the main page, there's an embedded iframe set up like this: <iframe src="facts.php" style="width:320px; height:500px; border:hidden" id="facts"> </iframe> Within that iframe, a jQuery function is implemented as follows: <script ty ...

What could be causing "Unknown property" errors when using unicode property escapes?

The MDN website provides examples of matching patterns with unicode support, such as: const sentence = 'A ticket to 大阪 costs ¥2000 ...

What causes z-index to be ineffective with sticky elements?

In my website, I've implemented rollover effects in a sticky footer and a responsive menu that stays at the top. However, when the menu is opened and extends over the footer, it covers everything except the rollovers. Closed navigation http://www.mus ...

Adding 7 days to a JavaScript date

Can you spot the bug in this script? I noticed that when I set my clock to 29/04/2011, it displays 36/4/2011 in the week input field! The correct date should actually be 6/5/2011 var d = new Date(); var curr_date = d.getDate(); var tomo_date = d.getDate( ...

Discover the ins and outs of the "DOM" within a string, treating it as HTML in AngularJS

Looking to extract data from a legal HTML string based on tags and attributes, but want to avoid using jQuery in favor of Angular. Are there built-in functions in Angular for this task? ...

Angular is encountering an issue where it is unable to read the value of a JavaScript function, despite the object having a value

I have developed some JavaScript functions that involve reading and writing to a JSON file, with the intention of calling them in an Angular environment (from TypeScript code) using the jsonfile library. Below is the code snippet: function savePatient(pa ...

A guide on accessing objects from an array in Vue.js

Wondering how to choose an object from an array in Vue.js: When the page loads, the selectTitle() function is triggered. I simply want to select a specific object (for example, i=2) from my 'titleList' array. However, at the moment, I am only re ...

Using VueJS: Passing a variable with interpolation as a parameter

Is there a way to pass the index of the v-for loop as a parameter in my removeTask function? I'm looking for suggestions on how to achieve this. <ol class="list-group"> <li v-for="task in tasks" class="list-group-item"> ...

The voracious nature of the `+` and `*` operators

There is a variable, const input = "B123213"; When using the following regex pattern, const reg = /\d+/; and executing String match function, console.log(input.match(reg)); The output returned is 123213, illustrating that the expression is gree ...

Exploring the Depths of Scope Hierarchy in AngularJS

Upon inspecting the _proto__ property of an object I created, it is evident that it has been inherited from Object. https://i.stack.imgur.com/hcEhs.png Further exploration reveals that when a new object is created and inherits the obj object, the inherit ...

What is the best way to send information from child components to their parent in React

I'm facing a scenario where I need to increase the parent value based on actions taken in the children components. Parent Component: getInitialState :function(){ return {counter:0} }, render(){ <CallChild value={this.state.counter}/> ...

How to properly handle file uploads and get the correct image path from Node Js (Express) to React Js?

Currently, I am working on my local system developing a file upload feature using node js. My project file structure looks like this: Project ..client .... source code of React App ..Server ....uploads ......avatar ........image.png ....index.js In this ...

Utilizing the random function in a loop can result in unpredictable and unexpected values

Why is it that I get numbers ranging from 17 to 70,000 in the three console.log statements? However, in the loop, y always seems to fall between 200 and 800. Why is that? console.log("RND " + Math.floor(Math.random()*5000)*17) console.log("RND " + Math ...

The Ajax call was successful but the callback function failed to return

I've been encountering some challenges with a small application I'm developing. After successfully setting it up to automatically populate one field with the same value entered in another field, I decided to integrate an AJAX request into the scr ...

Image Placement Based on Coordinates in a Graphic Display

Placing dots on a map one by one using CSS positions stored in arrays. var postop =[{'top':'23'},{'top':'84'},{'top':'54'},{'top':'76'},{'top':'103'}]; var ...