When you click the button, it will change colors. But when you click it again, it won't return to its original color

I am trying to implement a feature where clicking on the correct answer will change its color to green, while clicking on the wrong answer will change it to red. I also want to add an additional functionality: if the right-answer button is clicked twice, it should first change to a specific color on the first click and then turn white on the second click. However, upon testing this additional functionality, I encountered a bug where the button cannot return to its original color. I attempted to use hello to address this issue, but there seems to be a mistake somewhere...

let b = document.querySelectorAll('.false');
let hello = -1;
document.querySelector('.true').addEventListener('click', function() {
  if (hello === 0) {
    document.querySelector('.true').style.backgroundColor = 'white';
    document.getElementById('check').innerHTML = null;
  }
  hello = 0;
  document.querySelector('.true').style.backgroundColor = 'red';
  document.querySelector('#check').innerHTML = 'Correct!';
  document.querySelector('#check').style.color = 'green';
  for (let i = 0; i < b.length; i++) {
    b[i].style.backgroundColor = 'white';
  }
})

for (let i = 0; i < b.length; i++) {
  b[i].addEventListener('click', function() {
    if (hello === 1) {
      b[i].style.backgroundColor = 'white';
      document.getElementById('check').innerHTML = null;
    }
    hello = 1;
    b[i].style.backgroundColor = 'green';
    document.querySelector('#check').innerHTML = 'Incorrect.';
    document.querySelector('#check').style.color = 'red';
    b[b.length - i - 1].style.backgroundColor = 'white';
    document.querySelector('.true').style.backgroundColor = 'white';
  })
}
<!DOCTYPE html>

<html lang="en">

<head>
  <title>Trivia!</title>
</head>

<body>
  <h3>IP version</h3>
  <button class="false" style="background-color: white">IPv3</button>
  <button class="true" style="background-color: white">IPv4</button>
  <button class="false" style="background-color: white">IPv5</button>
  <p id="check"></p>

</body>

</html>

Answer №1

After running your if statement, there is an issue of styles being overwritten. There are two scenarios to consider:

  1. First time clicking the correct button,
  2. Second time clicking the correct button

A simple if - else statement can address this: (I have also adjusted some styling in your code where the correct button was red and wrong buttons were green.)

  let b = document.querySelectorAll('.false');
  let hello = -1;
  document.querySelector('.true').addEventListener('click', function () {
    if (hello === 0) {
      hello = -1;
      document.querySelector('.true').style.backgroundColor = 'white';
      document.getElementById('check').innerHTML = null;
    } else {
      hello = 0;
      document.querySelector('.true').style.backgroundColor = 'green';
      document.querySelector('#check').innerHTML = 'Correct!';
      document.querySelector('#check').style.color = 'green';
    }
    for (let i = 0; i < b.length; i++) {
      b[i].style.backgroundColor = 'white';
    }
  })

  for (let i = 0; i < b.length; i++) {
    b[i].addEventListener('click', function () {
      if (hello === 1) {
        b[i].style.backgroundColor = 'white';
        document.getElementById('check').innerHTML = null;
      }
      hello = 1;
      b[i].style.backgroundColor = 'red';
      document.querySelector('#check').innerHTML = 'Incorrect.';
      document.querySelector('#check').style.color = 'red';
      b[b.length - i - 1].style.backgroundColor = 'white';
      document.querySelector('.true').style.backgroundColor = 'white';
    })
  }
  <h3>IP version</h3>
  <button class="false" style="background-color: white">IPv3</button>
  <button class="true" style="background-color: white">IPv4</button>
  <button class="false" style="background-color: white">IPv5</button>
  <p id="check"></p>

Answer №2

To make the necessary change in your code, simply insert a return statement within the conditional check for hello === 0. Here's how it should look:

let b = document.querySelectorAll('.false');
let hello = -1;
document.querySelector('.true').addEventListener('click', function() {
  if (hello === 0) {
    document.querySelector('.true').style.backgroundColor = 'white';
    document.getElementById('check').innerHTML = null;
    return; // ADD THIS LINE
  }
  hello = 0;
  document.querySelector('.true').style.backgroundColor = 'red';
  document.querySelector('#check').innerHTML = 'Correct!';
  document.querySelector('#check').style.color = 'green';
  for (let i = 0; i < b.length; i++) {
    b[i].style.backgroundColor = 'white';
  }
})

// .......

Additionally, remember to swap the positions of 'red' and 'green' strings in your code that set the background colors, as currently the wrong button turns green instead of red when clicked incorrectly.

The corrected section of code looks like this:

let b = document.querySelectorAll('.false');
let hello = -1;
document.querySelector('.true').addEventListener('click', function() {
  if (hello === 0) {
    document.querySelector('.true').style.backgroundColor = 'white';
    document.getElementById('check').innerHTML = null;
    return
  }
  hello = 0;
  document.querySelector('.true').style.backgroundColor = 'green'; // CORRECTION MADE HERE
  document.querySelector('#check').innerHTML = 'Correct!';
  document.querySelector('#check').style.color = 'green';
  for (let i = 0; i < b.length; i++) {
    b[i].style.backgroundColor = 'white';
  }
})

for (let i = 0; i < b.length; i++) {
  b[i].addEventListener('click', function() {
    if (hello === 1) {
      b[i].style.backgroundColor = 'white';
      document.getElementById('check').innerHTML = null;
    }
    hello = 1;
    b[i].style.backgroundColor = 'red'; // CORRECTION MADE HERE
    document.querySelector('#check').innerHTML = 'Incorrect.';
    document.querySelector('#check').style.color = 'red';
    b[b.length - i - 1].style.backgroundColor = 'white';
    document.querySelector('.true').style.backgroundColor = 'white';
  })
}

Answer №3

You can also accomplish it like this.

document.querySelectorAll(".false").forEach((value) => {
  value.addEventListener("click", () => {
    let currentColor = document.getElementById(value.id);
    currentColor.style.backgroundColor =
      currentColor.style.backgroundColor === "red" ? "white" : "red";
  });
});

document.querySelectorAll(".true").forEach((value) => {
  value.addEventListener("click", () => {
    let currentColor = document.getElementById(value.id);
    currentColor.style.backgroundColor =
      currentColor.style.backgroundColor === "green" ? "white" : "green";
  });
});
<!DOCTYPE html>

<html lang="en">
  <head>
    <title>Quiz Time!</title>
  </head>

  <body>
    <h3>Favorite Color?</h3>
    <button id="1" class="false" style="background-color: white;">Blue</button>
    <button id="2" class="true" style="background-color: white;">Green</button>
    <button id="3" class="false" style="background-color: white;">Red</button>
    <p id="result"></p>
  </body>
</html>

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

Angular and Bootstrap work hand in hand to provide a seamless user experience, especially

I have been exploring ways to easily close the modal that appears after clicking on an image. My setup involves using bootstrap in conjunction with Angular. <img id="1" data-toggle="modal" data-target="#myModal" src='assets/barrel.jpg' alt=&a ...

Having trouble storing data accurately in local storage using React

I implemented a combination of useContext and useEffect to store useContext data in local storage, but I am facing challenges due to conditional rendering. The scenario involves displaying a sign-in button when the user is not logged in and a log-out butto ...

Divide a picture with the help of javascript

Is there a way to utilize JavaScript to extract sections of an image and save them in an array, then showcase them randomly on an HTML5 canvas? ...

Attempting to execute Gulp 4 in order to convert SCSS files into CSS

After attempting to run Gulp to convert SCSS to CSS, the process appeared to be successful without any errors. However, I encountered a problem where no CSS files were generated in the target folder. I even tried changing the output path, but the issue per ...

Ways to iterate through a buffer object byte by byte in JavaScript

Is it possible to read buffer line by line in JavaScript? I currently have a JavaScript buffer object. If I use console.log(buff) it will display something similar to this: <Buffer 0c 00 00 00 99 4e 98 3a f0 9d 09 3b 00 00 00 00 68 48 12 3c f0 77 1f ...

Personalized color palette for CSS styling

Is there a way to implement a color scheme selection feature on my HTML site using CSS? I currently have base.css, green.css, and orange.css files. By default, the site loads with the green color scheme. How can I allow users to switch to the orange color ...

Tips on how to center an image within a table cell:1. Insert the image

I've been attempting to center an image within a bootstrap4 table cell, but it keeps appearing on the left and even overlaps the border. I've tried adding inline styles like text-align: center; vertical-align: middle; both to the table cell HTML ...

Modify each combination of characters surrounded by two symbols within a string

How can I replace the string between two symbols in my Angular code? For example, how can I change "Hello "I am" software coordinator as "freelancer"" to "Hello {I am} software coordinator as {freelancer}" I have been trying to write the code for this, ...

Restrict the movement of an object in Three.js to stay on the surface of another

My goal is to be able to drag an object and have it snap to the surface of another. Whether it snaps upon release or updates live doesn't matter to me. The ultimate objective is to create a smooth shape in Blender, import it, and enable snapping whil ...

Displaying and concealing animation subcategories

I wanted to add animation to the sub-categories in my code snippet located at: this link so that they show up when I hover over the category name. Unfortunately, my current solution didn't produce the desired result. <script> $(document).ready ...

Using VueJs's createElement() to dynamically insert HTML content

I am currently working on a component that converts all icons to SVG format. By the end of my code, I have included the following: return createElement('i', '<SVG>CODE</SVG>' ) In the spot where the SPA ...

Merging Angular with jQuery: Organizing jQuery into a distinct file leads to the error message 'Property 'top' cannot be read because it is undefined.'

My project is based on AngularJS, and I've been trying to incorporate a jQuery code for a sticky sidebar feature. Strangely enough, when I tested my code on Plunkr, it works perfectly fine. However, when I try to implement it in my actual project, it ...

Can the value of a key automatically default to the parent's value if it is not found in the child?

When looking at the JSON example provided, is there a method to automatically switch back to the parent object key if the child object does not contain the key? // Example of i18n JSON "parent": { "foo": "foo", "bar": "bar", "child" ...

looping through javascript json arrays using foreach

I am facing an issue with a JSON array that is structured like this: [{"RegDate":"31-03-2011"},{"RegDate":"29-07-2011"},{"RegDate":"09-08-2011"},{"RegDate":"09-08-2011"},{"RegDate":"09-08-2011"},{"RegDate":"12-08-2011"},{"RegDate":"15-08-2011"},{"RegDate" ...

Obtaining weather information for a particular date through wunderground

Today marks my first experience using this wunderground service. My goal is to retrieve weather data under the following circumstances: Note : Today Date :2014-02-03 I am looking to access weather data ranging from 2014-01-21 to 2014-01-31, which fal ...

Is it possible to achieve seamless image transitions in Firefox like it does in Chrome?

To achieve the desired effect, you may need to use some javascript. Visit aditagarwal.com for more information. Styling with CSS: .images-wrapper{ position: fixed; left: 0; top: 80px; bottom: 0; width: 100%; height: 100vh; an ...

Animating a ThreeJS Mesh using the TweenMax scaling method

Having issues trying to implement a scaling translation to my mesh[0] using TweenMax. While other animations like rotation work fine, I encounter an 'Uncaught TypeError: Cannot assign to read only property 'scale' of object '#'&apo ...

What steps should I take to ensure the text layout algorithm effectively scales the text based on the "font size" option when using SVG paths?

I have included a fully functional JavaScript code snippet at the end of this post, demonstrating how Hebrew text can be displayed in a "stretched" layout design, as referenced here. The output shows the text in various font sizes: 32 The text appears mos ...

"Enhance your website with a dynamic animated background using Bootstrap container

I'm struggling to understand why the Bootstrap container is blocking the particles-js animation behind the text. I want the background surrounding the text to be animated as well... :/ Example Code: .gradient-bg { background: rgba(120, 87, 158, ...

Discover how to iterate through an array following a map operation and generate a new array based on conditional statements

data.risk.scatterIndices.investments.map((el: any) => el.name) || [] I have a mapping function that generates an array like this: ["pension","realestate","balance","kupot"] This is the condition I want to use t ...