JavaScript Quizzyquiz

As a beginner in programming, I am facing an issue while trying to recreate a quiz. The main problem is that upon selecting an answer, I should receive immediate feedback on whether the answer is correct or wrong. Additionally, the answers should be hidden initially, and only revealed after clicking the next button which hides the answers again.

Below is my code snippet:

const questions = [
    // Questions array containing various car-related questions
]

// JavaScript code for handling quiz functionality such as displaying questions and checking answers
*{
    // CSS styles for formatting the quiz layout
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>CarQuiz</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div id="container">
        <div id="message" class="hide">
            // HTML structure for displaying feedback messages
        </div>
        <div id="content">
            <img src="" alt="" id="image">
            <div class="text" class="hide">
                // HTML elements for displaying question, answers, and buttons
            </div>
        </div>
    </div>
    <script src="script.js"></script>
</body>
</html>

Answer №1

There may be a more efficient way to achieve your goal (some rewriting may be required later on), but here is one solution.

  1. Assign a hide class to your next button to make it invisible once the quiz loads.
  2. In your style.css, add !important to your .hide {...}. This will be explained later.
  3. Add the following line to your setNextQuestion() function declaration:
message.classList.add('hide');

This step is necessary to hide the message ("Well done!" / "Wrong!") when new questions are loaded. The inline display:flex in your #message has higher specificity than what .hide sets for display, hence the need for !important. This method provides a basic solution and may not be the most ideal.

  1. In your showQuestion(question) function declaration, replace this
answers.innerHTML += `<button class="btn">${answer}</button>`

with this

answers.innerHTML += `<button class="answer-btn btn">${answer}</button>
  1. In the same function, change this
const answerBtns = document.getElementsByClassName('btn')

to this

const answerBtns = document.getElementsByClassName('answer-btn')

The reason for this change is that the .btn class is used elsewhere (start, next), and you likely only want to target the buttons related to the answers.

  1. After the previous code line, add this
answers.classList.remove('hide');

This line is crucial due to the adjustments made in step 2. Without it, the questions would not appear as intended.

  1. Also in the same function, modify the click event attachment to individual answerBtns with the following changes (the ones marked with // new should be added):
Array.from(answerBtns).forEach(btn => {
    btn.addEventListener('click', () => {
        message.classList.remove('hide'); // new
        answers.classList.add('hide'); // new
        if (btn.textContent === questions[questionNr].correct) {
            message.style.display = 'flex'
            correct.style.display = 'flex'
            wrong.style.display = 'none'; // new
            const stats = document.getElementById('stats')
            stats.innerHTML = `${questionNr + 1}/${questions.length}`
        } else {
            message.style.display = 'flex'
            wrong.style.display = 'flex'
            correct.style.display = 'none'; // new
            stats.innerHTML = `${questionNr + 1}/${questions.length}`
        }
        nextButton.classList.remove('hide')
       // answers.style.display = "none"

    });
})

The additional lines serve to ensure that regardless of the answer correctness, questions are hidden, and the answer holder (message) is displayed. Depending on the outcome, the relevant message (correct/incorrect) is shown while hiding the opposite message.


Additional points to consider:

  • While the above steps fulfill the initial intention (hiding answers initially, displaying them upon clicking next, and hiding the button), it does not address showing the final result/score at the end of the quiz.
  • After the last question is answered, clicking the next button will trigger a console error as there are no more questions within your const questions. To resolve this issue, introduce a simple check after initializing the showQuestion(question) function, like so:
function showQuestion(question) {
    if(typeof question.question === 'undefined') {
        return false; // Consider including additional actions such as alerting the user or displaying the score.
    }

    // ... continue with the rest of your original code
}

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

Remove the post by utilizing the $.ajax function

I am just starting out with using $.ajax and I'm not very familiar with it. I have a button that is meant to delete a user post based on the article ID provided. <button type="button" onclick="submitdata();">Delete</button> When this but ...

Having trouble getting the .replace() Javascript function to work on mobile devices?

I have a code snippet for implementing Google Analytics. Here it is: $(function () { $('.plan-choose-btn a').bind('click', function(e) { //ga load image <% String myaccGAEventUrl = trackGoogleAnalyticsEvent(requ ...

Unable to retrieve the URL using the getDownloadURL function from Firebase

I have been using Firebase storage to successfully store images, however I am encountering an issue when trying to retrieve the image URL from a promise. const imageSaveHandler = (e) => { e.preventDefault(); const uploadTask = storage.ref(`i ...

Using jQuery to target form elements that have a specific class assigned to them

I am facing an issue with targeting input fields within a specific form on a page. The form has a certain class, let's say "has-error," and I want to remove this class from all the input fields in that form. I attempted the following code snippet: t ...

What is the best method for arranging the elements in this array?

In the process of enhancing my system, I am currently working on integrating a messaging feature. The main objective at this stage is to create a jQuery popup dialog that showcases the names of users who have exchanged messages with each other. Clicking on ...

Retrieving blog posts formatted in markdown from a centralized JSON file

My current setup involves using react-markdown to load markdown content from a JSON file. I have opted for a static site hosted on CloudFront to save money and eliminate server operation costs. All posts are compiled into a posts.json file which is then ...

What is the best way to eliminate the bottom border of an input field?

Seeking advice on how to eliminate the border-bottom of an input field when typing starts. .car-list-input { font-family: 'Source Sans Pro', sans-serif; border-radius: 3px; font-size: 14px; font-weight: 400 !important; height: 35px; ...

Need to monitor AJAX requests in Chrome on an iOS device?

I have implemented a method to intercept AJAX requests on my website by modifying the XMLHttpRequest.prototype open and send methods. This approach has been successful in all browsers I tested, except for Chrome on iOS (iPhone) where it seems to continuous ...

Using the includes method with a switch statement in Javascript

Hey there, I'm facing a bit of a challenge here. It seems like what I'm attempting to do might be more complex than I initially thought or my brain is just not cooperating. I'm currently working on using a switch statement to verify if a str ...

"Angular File Upload Made Easy with Drag-and-Drop Functionality and Cleverly Positioned

Encountering an issue with Angular File upload in conjunction with relatively positioned elements. The drop target is set to 100% width and height, absolutely positioned. While dragging a file over any non-relatively positioned element, the overlay functio ...

AJAX parameters for sending xmlhttp requests

I'm currently working on an AJAX function that dynamically changes the color of a specific button. However, I have only been able to achieve this in a static manner by manually inputting the values sent to the corresponding php script. My goal is to b ...

Transfer the values from identical textboxes to jQuery, and subsequently to a PHP page for saving them to a database

Here is a list of textboxes that I have: ` <table id="div1" style="width:100%;"> <tr> <td> <label>Question Text</label> </td> <td colspan="5"> ...

What is the recommended Vue js lifecycle method for initializing the materialize dropdown menu?

https://i.stack.imgur.com/cjGvh.png Upon examining the materialize documentation, it is evident that implementing this on a basic HTML file is straightforward: simply paste the HTML code into the body and add the JavaScript initializer within a script tag ...

Tips for effectively utilizing Timelinemax and Tween for object animation

Hello Amazing Stackoverflow community, I've been attempting to move my object in three.js to a specific point. I believe I need to utilize Tween.js for this task. However, in the tutorial I followed, they imported Tween Js but used 'timelinemax& ...

HTML features various product displays across multiple pages

I am struggling with the terminology for my issues. I am currently working on an e-commerce project aimed at displaying products. My goal is to have only 30 products shown on each page, with product 31-60 displayed on page 2 and product 61-90 displayed on ...

Refreshing Values in Arrays with PHP

Having a slight problem related to variable declaration and value within an array. Let me clarify: The scenario: There is a 'Require' statement at the top of my script containing an array with the following content: .... $oModules[5][' ...

Should the page.js in a Next.js App router be a server component?

Is it standard practice in Next.js 13 and above (App router) for the page.js of all routes/folders to be a server component? I know that it can be a client component with use client, but is this advisable or are there potential issues during the build proc ...

Avoiding GulpJs freezing with effective error handling techniques

I am currently in the process of converting my sass files to css and encountering some issues. Specifically, I am struggling with handling errors during the sass conversion process. Whenever there is an error, it causes gulp to hang, requiring me to rest ...

Rendering an object as a React child is not allowed (object found with keys {this}). To display multiple children, make sure to use an array instead of an object

Encountering an error: How can I resolve this issue in React? The file relates to the layout I am utilizing Visual Studio export default class Layout extends React.Component { constructor(props) { super(props); this.identify = this.identify.bi ...

Is it possible to retrieve data from a database using jQuery and store it in separate variables?

I am able to print out one field from a table, but I want to display all fields in separate tables. How can I achieve this? Below is my save/load code: // Save/Load data. $('').ready(function() { if($.cookie('code')) { $.aj ...