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

Invoke a controller in Prestashop by utilizing AJAX technology

I am struggling to figure out how to call the method / function in my controller. The controller is named TestController.php, and I also have files named Test.tpl and Test.js. Additionally, I am unsure of what to put in the URL field. My goal is to retrie ...

How can I update the image src in JavaScript and make sure the image refreshes properly?

I managed to update the image source in JavaScript code, changing it from: http://loclhost:8080/mvc/resources/pics/625bd317-b71c-4d74-aff2-248b86ff900b.jpg to http://loclhost:8080/mvc/resources/pics/4c1541ab-204c-4eff-b641-8527294e02cd.jpg Here is the ...

The issue of duplicate results appearing in the Wikipedia viewer persists even after conducting a second search

I have been working on a project to create a wiki viewer, but I've encountered an issue. Currently, I am utilizing the Wikipedia API. When a user enters a search query, they are presented with 5 possible articles (title and first sentence), and upon ...

Loading modules conditionally in Nuxt.js

In my Nuxt.js configuration, I have included a module for Google Tag Manager like this: modules: [ [ '@nuxtjs/google-tag-manager', { id: 'GTM-XXXXXXX' } ] ] Everything is functioning properly, but I am curious ab ...

Clear Vuex state upon page refresh

In my mutation, I am updating the state as follows: try { const response = await axios.put('http://localhost:3000/api/mobile/v3/expense/vouchers/form_refresh', sendForm, { headers: { Accept: 'application/json', 'C ...

Is there a way to create a universal getter/setter for TypeScript classes?

One feature I understand is setting getters and setters for individual properties. export class Person { private _name: string; set name(value) { this._name = value; } get name() { return this._name; } } Is there a w ...

Encountering the error "ReferenceError: Cannot access 'data' before initialization" during deployment on Vercel

I encountered a problem with my project after trying to implement dynamic routing. Initially, everything was working fine locally and during deployment. However, when I attempted to incorporate dynamic routing, errors started to occur. Unfortunately, I am ...

Looking to incorporate AAD calling functionality in a React and Node application by utilizing the Graph API for communication/calls

As a newcomer to Microsoft Azure and its services, I recently registered an application with Azure. However, when attempting to integrate a call feature in my Web App using the graph API '/communication/calls', I encountered the following error m ...

What is the best way to adjust the fill animation of an inline svg based on the movement of the mouse within the parent div?

Can the fill of an inline SVG path be animated to change as the mouse moves across the page? ...

The iframe is not large enough to contain all the HTML content

I'm encountering a problem with a website I'm currently developing - specifically, I am struggling to embed an HTML document into an iframe in a manner that fills the entire page. Additionally, I am utilizing Angular to retrieve the HTML document ...

Creating an array object in JavaScript is a straightforward process that involves using the array

Looking to achieve the following object list structure: myObj = {"foo":[1,2,3,4], "bar":[3,5,7,8]} Initial attempt was unsuccessful: var myObj = new Object(); myObj["foo"].push(1) myObj["foo"].push(2) #...etc Seeking guidance on the correct m ...

Using JavaScript to apply styling on images with overlays

I am currently facing an issue with placing an overlay on top of a background image. Despite my efforts, I am unable to get the background color to appear on top of the image. Any helpful suggestions on how to resolve this would be greatly appreciated. M ...

Is there a way to identify the element causing an error in promise.map and then either log it to the console or skip it using code?

When running the code provided below, I encounter a 500 error for certain URLs in my list due to the structure of the page. The error occurs specifically on the line .map((htmlOnePage, index) => when some URLs lead to invalid pages, causing the prog ...

Aligning an object in ThreeJS to always face the camera, ensuring it is perfectly straight and flat

Reviewing this demo http://codepen.io/anon/pen/JdmMPW, I am working on creating a camera orbiting around a sphere with text labels/satellites (represented by the plane object) that should always face the camera. function render() { marker.lookAt(camera.p ...

The issue of checkboxes not being sorted properly in Slick Grid

Currently, I am working on resolving a sorting issue within one of our applications using Slick Grid for grid implementation. The existing sort function, although functional, presents a challenge. While it successfully sorts columns, the checkbox associate ...

Choosing an Array of Integers in PostgreSQL: A Guide

My goal is to extract arrays of integers from a table in this format: [1, 2, 3] I attempted the following query: (SELECT array_to_json(array_agg(row_to_json(s))) FROM( SELECT specialty FROM talent_specialty WHERE userid = 840 )s); This is the result r ...

Learn how to access the data stored in an array within a function using PHP

I have been diving deeper into arrays and foreach statements to enhance my skillset. Within one of my files, I've defined the following class and function: class Onboarding_Dashboard { static function dashboard_onboarding_content() { $items = a ...

Creating prototypes for objects starting from an empty state

Below is the custom code structure I have created: module.exports = (function() { Function.prototype.extend = function(obj) { for (var prop in obj) { this[prop] = obj[prop]; } } })(); var CustomHelpers = {}; CustomHelpers.prototype.get ...

Loading indicator displayed at the top of a div using JavaScript/jQuery

My current challenge involves implementing a progress bar, similar to the pace.js progress bar. The issue arises when the browser is refreshed, as the pace.js progress bar loads on top of the body instead of within a specified div. It is important that the ...

Use Entity Objects instead of Strings in your Ajax requests for improved data handling

As I work on developing a web portal with Freemarker(FTL) as the front end technology, my project revolves around a single FTL page that utilizes a wizard to manage various user requests. The back end is structured using the Spring MVC pattern, where contr ...