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

Organizing layers with Leaflet's layerGroup controls

I am working with a series of Leaflet FeatureGroups, each made up of GeoJSON layers. These FeatureGroups have similar concepts but need to be kept separate for control purposes. I also require the ability to toggle all FeatureGroups on and off simultaneous ...

When utilizing jQuery to add a <li> element, it suddenly vanishes

? http://jsfiddle.net/AGinther/Ysq4a/ I'm encountering an issue where, upon submitting input, a list item should be created with the content from the text field. Strangely, it briefly appears on my website but not on the fiddle, and no text is appen ...

The new mui v5 Dialog is having trouble accepting custom styled widths

I am facing an issue with my MUI v5 dialog where I cannot seem to set its width using the style() component. import { Dialog, DialogContent, DialogTitle, Paper, Typography, } from "@mui/material"; import { Close } from "@mui/icons- ...

Transferring a Query between Domains with the Help of JavaScript

It is necessary to develop a function that generates a query based on the user's input of "Test" in an INPUT on Site A (SiteA.com) and then redirects to Site B within the same window, passing along the query (SiteB.com/search.aspx?k=test). Code snipp ...

A collection of functions embedded within a JSON data structure

I am working with a website that provides data in a JSON-like format similar to the following: { "name":"tom jones", "no": 123, "storedproc": function(){ callbuyer(0123); } } Currently, I am using $. ...

Issue with breakpoints functionality in MUI v5 and React project

I've been attempting to utilize breakpoints for responsive design on my website, but unfortunately, it doesn't seem to be working correctly. Every time I implement a breakpoint, the entire page goes blank. Below is the code snippet I am working w ...

What is the reason for the getter not being able to retrieve the value

I am experiencing an issue with a getter that returns an array of objects. The challenge I face is that I need to display past and current warnings in separate components. The getter currently only retrieves the current warning and ignores any past warnin ...

Element Proxy

I decided to experiment and see how a library interacts with a video element that I pass to it. So, I tried the following code: const videoElement = new Proxy(document.querySelector('video'), { get(target, key) { const name = typeof ...

Error in Node and Express: Unable to access route

Currently, I am in the process of developing an Express application and running into some obstacles with routing. While my '/' route is functioning perfectly fine, other routes are not working as expected. Despite researching similar questions fr ...

Utilizing a filter within the ng-model directive

I have a question about using a filter with an h3 element. Here is the code snippet: {{ event.date | date:'dd-MM-yyyy' }} It's working perfectly fine and Angular is formatting the date as expected. However, when I try to use the same filte ...

My requests are failing because jQuery AJAX does not send hashtag symbols

There's a challenge I'm facing while working with Elixir Phoenix and React.JS. The Token I have includes hashtags, and when I send a request to verify it, the hash symbols and everything after them are not being sent, causing the request to fail. ...

Streamlining all icons to a single downward rotation

I am currently managing a large table of "auditpoints", some of which are designated as "automated". When an auditpoint is automated, it is marked with a gear icon in the row. However, each row also receives two other icons: a pencil and a toggle button. W ...

"Can you help me understand how to establish a character limit for the MUI autocomplete

Hey everyone, I have successfully created an auto-complete feature using Material UI and an API. Now, I am facing a challenge where I need to limit the suggestions returned by the autocomplete to only show matches when the user types at least 3 letters. Ca ...

JavaScript Age confirmation Overlay

I designed an age verification popup with the help of some online tutorials and a friend due to my limited knowledge of JavaScript. Check it out live here- My issue is that I want this popup to load/appear after the page content loads, but I'm not s ...

Discovering the meeting point where two dives converge

Is there a method to change the color of the overlapped common part of two animated circles? ...

Eliminate redundant XML entries when using jQuery autocomplete

Does anyone know how to prevent duplicate records from appearing in a jQuery autocomplete dropdown? I am pulling data from an XML file and want to ensure that each record is unique and only displayed once. You can see the issue here ...

Guide to verifying the presence of cookies by name in the browser and granting access to the specific page accordingly

In the process of developing an authorization system with Express, Node, and MySQL, I decided to utilize JWT tokens for user authorization. After successfully storing the JWT token in cookies, my next step is to verify if the token exists in the cookie b ...

Improved method for retrieving a subtask within a personalized grunt task?

As someone who is just starting out with Grunt and has only created a few custom grunt tasks, I've come up with what might be seen as an unconventional solution for traversing the initConfig to subtasks. My approach involves putting together a regex a ...

The module 'NgAutoCompleteModule' was declared unexpectedly by the 'AppModule'. To fix this issue, make sure to add a @Pipe/@Directive/@Component annotation

Currently, I am attempting to integrate an autocomplete feature into my Angular 2/4+ project. Despite trying various libraries, none of them seem to be working correctly. Each one presents me with a similar error message: Unexpected module 'NgAutoCom ...

Why is it necessary in JavaScript to reset the function's prototype after resetting the function prototype constructor as well?

Code is often written in the following manner: function G() {}; var item = {...} G.prototype = item; G.prototype.constructor = G // What is the purpose of this line? Why do we need to include G.prototype = item before resetting the prototype? What exact ...