The button's color cannot be modified due to a malfunctioning event script that is not

Seeking an explanation for why my current implementation isn't working. I'm attempting to create a quiz with a multiple choice section where the correct answer turns green when clicked, and incorrect answers turn red. Despite validating the code and finding no errors, the buttons remain non-interactive. Can someone help me identify what might be going wrong here?

    <!DOCTYPE html>

<html lang="en">
    <head>
        <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap" rel="stylesheet">
        <link href="styles.css" rel="stylesheet">
        <title>Trivia!</title>
        <script>
            document.addEventListener('DOMContentLoaded', function(){
                let incorrects = document.querySelectorAll(".incorrect_answer");
                incorrects.addEventListener('click', function() {
                let clicked = event.srcElement;
                clicked.style.backgroundColor = 'red';
            });
                let correct = document.querySelector(".correct_answer");
                correct.addEventListener('click', function() {
                    correct.style.backgoundColor = 'green';
            });

            });
        </script>
    </head>
    <body>
        <div class="header">
            <h1>Trivia!</h1>
        </div>

        <div class="container">
            <div class="section">
                <h2>Part 1: Multiple Choice </h2>
                <hr>
                <h3>How many species of Dolphin are there?</h3>
                    <button class="correct_answer">42</button>
                    <button class="incorrect_answer">53</button>
                    <button class="incorrect_answer">24</button>
                    <button class="incorrect_answer">11</button>
            </div>

            <div class="section">
                <h2>Part 2: Free Response</h2>
                <hr>
                <!-- TODO: Add free response question here use input tags -->
            </div>
        </div>
    </body>
</html>

Answer №1

  1. The console is showing errors because the dev tools were not opened
  2. You cannot apply addEventListener to a list of items
  3. You are trying to access the event variable which is undefined
  4. There was a typo in the spelling of backgroundColor

document.addEventListener('DOMContentLoaded', function() {
  let incorrects = document.querySelectorAll(".incorrect_answer");
  incorrects.forEach(item => item.addEventListener('click', function(event) {
    let clicked = event.srcElement;
    clicked.style.backgroundColor = 'red';
  }));
  let correct = document.querySelector(".correct_answer");
  correct.addEventListener('click', function() {
    correct.style.backgroundColor = 'green';
  });
});
<body>
  <div class="header">
    <h1>Trivia!</h1>
  </div>

  <div class="container">
    <div class="section">
      <h2>Part 1: Multiple Choice </h2>
      <hr>
      <h3>How many species of Dolphin are there?</h3>
      <button class="correct_answer">42</button>
      <button class="incorrect_answer">53</button>
      <button class="incorrect_answer">24</button>
      <button class="incorrect_answer">11</button>
    </div>

    <div class="section">
      <h2>Part 2: Free Response</h2>
      <hr>
      <!-- TODO: Add free response question here use input tags -->
    </div>
  </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

"Enhanced file manager: Elfinder with multiple buttons to seamlessly update text input fields

Every button is responsible for updating the respective element: <input type="text" id="field" name="image" value="<?php echo @$DuzenleSonuc[0]['image']; ?>" /> I need to ensure that each button updates the correct field: onclick ...

Adding elements to my state array - Utilizing Nextjs/React/Javascript

After fetching data from 2 different APIs that each return an object, I have stored them in separate states. Now, I want to merge these two objects into a single state that contains both of them as an array. However, when I try to do this, the second obj ...

Why is the feedback section showing a horizontal scrollbar?

I'm puzzled as to why a horizontal scrollbar is appearing in the feedback section. I've examined the elements but can't seem to pinpoint the issue. ...

Tips for maintaining the size of a div container

Take a look at the following code snippet: <head> <title></title> <style> .section_divs { background-color: lightblue; float: left; } #section_empty { background-color: tomato; width ...

Verify the form data before triggering the ajax call with just one click

Ensuring that all required areas are completed in a form is crucial. The form needs to be validated properly to either reject the request with a message showing what information is missing, or submit it successfully... The rejection process works well as ...

Why does my Angular service throw an error stating "undefined is not a function" when passing my function as an argument?

I am currently working on implementing factory and two constructor patterns in Angular. My goal is to convert the factory into an Angular service. Below is a simplified version of the code I am working with: function processFactory () { // some code ...

Leveraging Vue js components while utilizing it from a content delivery network (CDN

I'm attempting to utilize the ButtonCounter component as a demonstration (source: https://vuejs.org/guide/essentials/component-basics.html#defining-a-component), but I am facing difficulties in getting it to function properly. I am utilizing Vue.js 3 ...

Scaling a mesh and BufferGeometry vertices using THREE.OBJLoader

Utilizing the THREE.OBJLoader, I successfully loaded a 3D model into my scene. Subsequently, I have the necessity to scale it by 10 and then extract its vertices position. I am aware that the THREE.OBJLoader provides a BufferGeometry, allowing me to acce ...

Using a Material-UI component to activate a React Router Link

Currently, I am facing an issue while using material-ui components in react with react-router. The problem arises when I try to display list-items that double up as link elements but also have a submenu inside which should not activate the parent link. Unf ...

In internet explorer with AJAX, the UI is refreshed by Javascript only when an alert() function is triggered

Having an issue in Internet Explorer, works perfectly in Firefox. There is a javascript function that updates the UI (screen content) before an AJAX call. However, it does not update the UI unless an alert box prompt is used. Without the alert box, the UI ...

Techniques for capturing Django's output from an Ajax request

I've been trying to utilize Ajax for converting my form data to JSON and sending it to my Django view. However, I'm encountering an issue where after successful processing in the view, I am returning a template response with some context data tha ...

How can I wait for an onclick action to pause, loop, or continue inside of a loop?

The form's onsubmit function triggers a pop-up message asking the user if they want to proceed before submitting the form. This requires the onsubmit function to wait for the user's final input in order to fully execute the form. Here is the cod ...

Make the height of the CSS div fill the remaining space and allow scrolling once the maximum height of the screen is reached

I've scoured the internet high and low for a solution to my problem, but I just can't seem to find anything that fits my needs perfectly. The answers I have come across are either outdated or not quite what I'm looking for. I'm really h ...

Tips for including a lang attribute in HTML tags within Next.js

When I ran a performance check on my Next.js portfolio site, I discovered that the main index.html is missing a lang attribute. This absence results in a deduction from the accessibility score. I could add the locale by configuring i18n setup in the next. ...

Using clip-path in SVG works perfectly on images, but unfortunately it does not work on div

I came across an interesting example on MDN about using a clip-path SVG on an image. However, it seems that the same clip-path does not work properly when applied to a div. Can anyone shed some light on: The reason why this code is not achieving the inte ...

Using TypeORM to Retrieve Data from Many-to-Many Relationships with Special Attributes

Hey there, I'm diving into the world of TypeORM and could really use some guidance. I've been attempting to set up many-to-many relationships with custom properties following the instructions provided here However, I've run into a few iss ...

Guide on displaying the appropriate child "div" with jQuery?

I am facing a challenge with my two dependent dropdowns that toggle the visibility of divs based on user input. The first div is functioning correctly, however, every time the user makes a selection in the second div, it impacts the first div. $(docume ...

What is the best way to instruct jQuery to disregard an empty server response?

After examining this piece of code: $.ajax({ type: "POST", url: theRightUrl, data: whatToPost, logFunction: whatever, suppressSuccessLogging: !0, dataType: "html" }); I encountered an issue where Firefox displays a "no element ...

What is the simplest method for preserving the Redux state?

What is the most efficient method to maintain state in Redux even after a website refresh? I would prefer not to rely on redux-persist if there are alternative options available. ...

From HTML to Python CGI to communication with a Serial port

I am having an issue running a Python CGI script to send data to a serial port. Whenever I try to open and set the serial port to a variable, the HTML server crashes. Below is the code snippet that receives a color (red, blue, green) from the HTML page: ...