Javascript functions triggering repeatedly

I'm working on creating a fun trivia quiz using JavaScript functions. Each question involves globally defined functions called "right" and "wrong" that are supposed to update the score accordingly. However, I've run into an issue where the quiz seems to be listening to the wrong set of functions with each new question. Despite trying several solutions, I haven't been able to resolve this problem. My tutor and I spent hours brainstorming without success, so I decided to seek help here.

We both assumed that enclosing the event listeners in curly brackets would prevent them from capturing clicks from other functions...

Any suggestions or advice on how to fix this would be immensely appreciated!!

Please Note: The third and fourth question functions follow the initial format used for the first and second questions.


            // Your JavaScript code goes here...
        

            <div class="time"></div>
            <div id="main">
                ...
            </div>
        

Answer №1

Instead of constantly adding new click handlers without removing the old ones, a more efficient approach would be to treat questions and answers as data instead of code. By defining a structured data format that includes all questions, answers, and correct responses, you can avoid unnecessary repetition.

For example, create an array like this:

var questions = [{ 
    question: "What is the best selling car of all time?", 
    answers: ["Toyota Camry", "Ford F-150", "Honda Civic", "Toyota Corolla"],
    correct: 3 // note: first answer has index 0
}, { 
    question: "First introduced in 1974, which iconic hatchback still remains popular today?",
    answers: ["Ford Mustang", "Volkswagen Golf", "Toyota Celica", "Fiat 500"],
    correct: 1
}, {
    question: "What is the world's fastest production car as of July 2020?",
    answers: ["Koenigsegg Agera RS", "Hennessy Venom GT", "Buggatti Chiron Super Sport", "Lamborghini Aventador"],
    correct: 2
}, { 
    question: "What 70s car is known for its suicide doors and convertible top?",
    answers: ["Lincoln Continental", "Buick Rivera", "Ford Thunderbird", "Oldsmobile Toronado"],
    correct: 0
}];

With this structure in place, all you need to do is iterate through the array from one question to the next by incrementing the index.

It's also recommended to give users some time to see the outcome of their answers before moving on to the next question. Displaying a new question with a "Correct" message before the user has responded can be confusing.

Below is an implementation using just one click handler to handle all four answer buttons.

Include the following JavaScript code:

// JavaScript code here...

And use the following HTML template:

Time: <span class="time">60</span><br>
Score: <span id="score">0</span><br>
<div id="question"></div>
<button class="answer">A</button> <span class="text"></span><br>
<button class="answer">B</button> <span class="text"></span><br>
<button class="answer">C</button> <span class="text"></span><br>
<button class="answer">D</button> <span class="text"></span><br>
<div id="answer-result"></div>

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

Filter out all elements that come before the comma in the sorted array's output

Looking for a solution to modify my code so the output is just "Bothell" without the comma and count part. let As = document.getElementsByTagName('a'); let towns = new Map(); for(let a of As) { let town = a.textContent.split(',') ...

Converting a string containing multiple objects into an array with unique keys

I have a string with multiple objects and I need to add these objects into an array with different values. The data is received from the cart, so the number of objects can vary. For example: {"hidden_product_name":"productA","productId":"120","product_sk ...

Buttons and links with intricate geometries

I am currently developing a web application using Java/JSF and I am interested in finding out about technologies that would allow me to define intricate shapes as clickable buttons or links. Right now, my only option is to split an image into smaller trans ...

JavaScript code in AJAX response functions properly in browsers like Firefox, Chrome, and Opera. However, it encounters issues in Internet Explorer 11, displaying an error message stating

After searching through various posts, I was unable to find a solution to my question. My query involves requesting a jQuery Datepicker via AJAX. I have provided an example for you to review in Firefox, Chrome or Opera: Ajax javascript example Unfortuna ...

Transform an object containing key-value pairs into an array of objects that include the key name and its corresponding value

My mind is spinning with this problem... I'm struggling to transform the req.query I receive in Express, which is an object, into an array of objects. I need to pass these to SQL Server as inputs for stored procedures. Here is the data I have - { ...

Looking to add some movement to your website? Learn how to make an image track your mouse pointer in a specific section of your webpage

I'm just starting out with web design and javascript, so please be patient. My goal is to have an image follow the mouse pointer only when it's within a specific section of my website. I've managed to make the image track the mouse cursor ...

Developing Reactive Selections with Material-UI is made easy

After spending about 5 hours on a task that I thought would only take 15 minutes, I still can't figure out the solution. The issue is with my React App where I have two dropdowns in the Diagnosis Component for users to select Make and Model of their a ...

Display or conceal elements using the unique identifier selected from a dropdown menu in JavaScript

I have been searching the internet for a solution to my issue but nothing seems to be working. Here is the problem: Unfortunately, I cannot modify the TR TD structure and am unable to use DIVs. I am trying to dynamically display certain TD elements based ...

Using AngularJS to bind models to a multidimensional array

As I am new to angular js, please bear with me. In my view, I have a grid of text input boxes that I would like to map to a 2D array in my controller or something similar in java script. The code in my view is as follows: <div ng-repeat="row in [1,2,3, ...

Hover over the text to disable the input element and display it as a textbox

Currently, I have a situation where I have two text boxes - when text is entered into textbox1, textbox2 becomes disabled as expected. However, my second requirement is that upon disabling textbox2, hovering over it should display the message "You can ente ...

assigned to a variable and accessed in a different route

Why does the "res.username" variable return as undefined in the second route even though my user needs to login before accessing any route? router.post('/login', passport.authenticate('local'), function(req, res) { res.username = r ...

HTML: Organize a slightly intricate column in a table

I am facing an issue with sorting columns in an HTML table that has 2 headers row: <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="styles.css"> </head> <body> <table ...

Utilizing Firebase objects across multiple files: A comprehensive guide

I apologize for my ignorance, but as I am teaching myself, I have not been able to find the answer in the available documentation. My current project involves developing a Vue application with Firebase as the backend. To utilize Firebase services, you mus ...

Unable to remove jQuery variable using jQuery .remove() method

My goal is to remove the $movieDiv that appears when I click "#buttonLicensedMovie". It successfully appends to the html and the button hides as expected. However, I am encountering an issue when clicking the anchor tag with id "licensedMovie1", the $movie ...

Launching event handlers and applying CSS classes within a single scenario

How can I toggle the visibility of a button based on form field validation in JavaScript? I want to show or hide the button when the .confirm button is clicked, and if the form is valid, add a checkmark to the body element through event listener. The issu ...

javascript - The Key Pair of a Jquery Object is Not Defined

I'm currently going through an HTML element, which is an input field using jQuery, but I keep encountering an error. Here's the code snippet: $(".submit_button").on("click touch", function(e){ e.preventDefault(); var formdat ...

Resizing the background while scrolling on a mobile web browser

My website background looks great on desktop, but on mobile (using Chrome) the background starts to resize when I scroll, mainly due to the browser search bar hiding and reappearing upon scroll. Is there a way to prevent my background from resizing? Check ...

Using an array of objects to set a background image in a Bootstrap carousel using jQuery: a step-by-step guide

I have an array of items, each containing a background property with a URL to an image. Here is my array: https://i.sstatic.net/jfrV0.png Here is the HTML structure: <div id="myCarousel" class="carousel slide" data-ride="carousel"> <ol ...

Is there a method to prevent the repetition of this loop?

I have a question regarding my React app development. I am currently using useEffect to loop through six items every time, even when only one item has changed. How can I optimize this so that only the variable that was changed in the reducer function is ...

Oops! An issue has occurred where I am unable to access certain properties (specifically 'Symbol(__APOLLO_CONTEXT__)') while utilizing the Apollo provider

When attempting to implement a query in my upcoming app, I encountered an error that reads: Error: Cannot read properties of undefined (reading 'Symbol(APOLLO_CONTEXT)') This is the setup of my Apollo client: import { ApolloClient, InMemoryCache ...