What could be causing the lack of color change in my boxes even after confirming the prompt?

function changeColor() {
if (confirm("Press a button!") == true) {
  if(this.style.backgroundColor == "white")
    this.style.backgroundColor = "yellow";
  else if(this.style.backgroundColor == "yellow")
    this.style.backgroundColor = "red";
  else if(this.style.backgroundColor == "red")
    this.style.backgroundColor = "" 
  else
    this.style.backgroundColor = "";
} else {
  txt = "You pressed Cancel!";
}

  if (confirm('Are you sure you want to save this thing into the database?') == true) {
    // Save it!
  } else {
    // Do nothing!
  }
}

var boxes = document.getElementsByClassName("foo");
for (i = 0; i < boxes.length; i++) {
  boxes[i].addEventListener("click", changeColor);
}
.foo {
  float: left;
  width: 30px;
  height: 30px;
  margin: 5px;
  border: 1px solid rgba(0, 0, 0, .2);
  border-radius: 25%;
}

.white{
  background: #FFFFFF;
}

.whole {
  float: left;
  width: 900px;
  height: 900px;
  margin: 5px;
  border: 1px solid rgba(0, 0, 0, .2);
}
<div class="whole">
  <div id="centerbox1" class="foo white">A1</div>
  <div id="centerbox2" class="foo white">A2</div>
  <div id="centerbox3" class="foo white">A3</div><br><br>

  <div id="centerbox4" class="foo white">B1</div>
  <div id="centerbox5" class="foo white">B2</div>
  <div id="centerbox6" class="foo white">B3</div>
</div>
There seems to be an issue with the prompts and conditions not changing the color of the boxes as expected. The code was designed to change the colors when the user confirms a prompt, but for some reason, the behavior is not working as intended. Any insights on why this might be happening would be greatly appreciated. For example, when clicking on a square, it should prompt a yes or no response, resulting in the color changing to yellow. Clicking on the same square again, which is now yellow, should prompt another confirmation and change the color back to the original color. This question serves as a follow-up to the query found at div onclick prompts yes or no, if yes, div change to different color

Answer №1

Success! This solution worked perfectly for me.

The Breakdown:

  1. One key observation was that JavaScript was unable to access the element.style property from the .white class directly, but including inline CSS for each element resolved this issue. A live example showcasing this can be found in the linked jsfiddle.

  2. Another crucial aspect was identifying the improper use of the this scope within the function without defining its context. By passing the appropriate this argument to the click event handler and then replacing it with e, the functionality was successfully rectified.

function myFunction(e) {
  if (confirm("Press a button!") == true) {

    if (e.style.backgroundColor == "white")
      e.style.backgroundColor = "yellow";
    else if (e.style.backgroundColor == "yellow")
      e.style.backgroundColor = "red";
    else if (e.style.backgroundColor == "red")
      e.style.backgroundColor = "white"
    else
      e.style.backgroundColor = "white";
  } else {
    txt = "You pressed Cancel!";
  }

  if (confirm('Are you sure you want to save this thing into the database?') == true) {
    // Save it!
  } else {
    // Do nothing!
  }
}

var blocks = document.getElementsByClassName("foo");
for (i = 0; i < blocks.length; i++) {
  blocks[i].addEventListener("click", function() {
    myFunction(this);
  });
}
.foo {
  float: left;
  width: 30px;
  height: 30px;
  margin: 5px;
  border: 1px solid rgba(0, 0, 0, .2);
  border-radius: 25%;
}

.whole {
  float: left;
  width: 900px;
  height: 900px;
  margin: 5px;
  border: 1px solid rgba(0, 0, 0, .2);
}
<div class="whole">
  <div id="centerbox1" class="foo" style="background:white;">A1</div>
  <div id="centerbox2" class="foo" style="background:white;">A2</div>
  <div id="centerbox3" class="foo" style="background:white;">A3</div><br><br>

  <div id="centerbox4" class="foo" style="background:white;">B1</div>
  <div id="centerbox5" class="foo" style="background:white;">B2</div>
  <div id="centerbox6" class="foo" style="background:white;">B3</div>
</div>

Answer №2

function manipulateColor(e) {
  if (confirm("Press a button!") == true) {

    if (e.style.backgroundColor == "white")
      e.style.backgroundColor = "yellow";
    else if (e.style.backgroundColor == "yellow")
      e.style.backgroundColor = "red";
    else if (e.style.backgroundColor == "red")
      e.style.backgroundColor = ""
    else
      e.style.backgroundColor = "";
  } else {
    txt = "You pressed Cancel!";
  }

  if (confirm('Are you sure you want to save this thing into the database?') == true) {
    // Save it!
  } else {
    // Do nothing!
  }
}

var blocks = document.getElementsByClassName("box");
for (i = 0; i < blocks.length; i++) {
  blocks[i].addEventListener("click", function() {
    manipulateColor(this);
  });
}
.box {
  float: left;
  width: 30px;
  height: 30px;
  margin: 5px;
  border: 1px solid rgba(0, 0, 0, .2);
  border-radius: 25%;
}

.white {
  background-color: white;
}

.container {
  float: left;
  width: 900px;
  height: 900px;
  margin: 5px;
  border: 1px solid rgba(0, 0, 0, .2);
}

.purple {
  background: #ab3fdd;
}

.wine {
  background: #ae163e;
}
<div class="container">
  <div id="box1" class="box" style="background:white;">A1</div>
  <div id="box2" class="box" style="background:white;">A2</div>
  <div id="box3" class="box" style="background:white;">A3</div><br><br>

  <div id="box4" class="box" style="background:white;">B1</div>
  <div id="box5" class="box" style="background:white;">B2</div>
  <div id="box6" class="box" style="background:white;">B3</div>
</div>

This is the solution I was looking for!


     <!doctype html>
<html>
<head>
<script language ="javascript">
function manipulateColor(e) {
  if (confirm("Press a button!") == true) {

    if (e.style.backgroundColor == "white")
      e.style.backgroundColor = "yellow";
    else if (e.style.backgroundColor == "yellow")
      e.style.backgroundColor = "red";
    else if (e.style.backgroundColor == "red")
      e.style.backgroundColor = ""
    else
      e.style.backgroundColor = "";
  } else {
    txt = "You pressed Cancel!";
  }

  if (confirm('Are you sure you want to save this thing into the database?') == true) {
    // Save it!
  } else {
    // Do nothing!
  }
}

var blocks = document.getElementsByClassName("box");
for (i = 0; i < blocks.length; i++) {
  blocks[i].addEventListener("click", function() {
    manipulateColor(this);
  });
}
</script>


<style type="text/css">
.box {
  float: left;
  width: 30px;
  height: 30px;
  margin: 5px;
  border: 1px solid rgba(0, 0, 0, .2);
  border-radius: 25%;
}

.white {
  background-color: white;
}

.container {
  float: left;
  width: 900px;
  height: 900px;
  margin: 5px;
  border: 1px solid rgba(0, 0, 0, .2);
}

.purple {
  background: #ab3fdd;
}

.wine {
  background: #ae163e;
}

</style>
</head>

<body>
<div class="container">
  <div id="box1" class="box" style="background:white;">A1</div>
  <div id="box2" class="box" style="background:white;">A2</div>
  <div id="box3" class="box" style="background:white;">A3</div><br><br>

  <div id="box4" class="box" style="background:white;">B1</div>
  <div id="box5" class="box" style="background:white;">B2</div>
  <div id="box6" class="box" style="background:white;">B3</div>
</div>
</body>
</html>

This is my HTML code that doesn't work even though I copied and pasted the code snippet

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

Connecting via web sockets through SSL is not functioning properly

My Web Socket functions correctly in both the localhost and production environments (https://www.example.com). However, upon deploying the same code to the pp environment (), I encounter the error message: WebSocket handshake - Unexpected response code: 4 ...

A PHP mishap causing unexpected errors

My login page confirmation code is giving me an error when trying to log in: Warning: mysql_fetch_row() expects parameter 1 to be resource, boolean given in /home/u133082736/public_html/login.php on line 14 This is the snippet of my code that's ca ...

React 16 is encountering a discrepancy due to the absence of the data-reactroot attribute

As I was in the midst of updating some apps to React 16, I couldn't help but notice that the data-reactroot attribute is no longer present on the main root element. Although not a critical issue, it seems like we had certain code and styles that reli ...

Finding the name of a particular item in an array and increasing its value - a step-by-step guide

For a homework project, I am developing a straightforward cart system. Could someone advise me on the best approach to retrieve an item from an array and increment its value by one? The array contains 25 items, each with a unique name but without any IDs a ...

Guide on removing the parent JSON array while retaining the child JSON array

I have been searching for a solution to remove specific JSON array elements, but I have not found one yet. Here is the JSON data I am working with: [ { "KODE": [ { "name": "kode", "value": [ ...

PHP - display the modified page with the updates applied

I currently have an HTML page where users can input information and submit a form to change database information. Typically, the submit button calls a PHP file on the server to process the data. However, I am looking for a way for this PHP file to return t ...

Is there a jQuery or Javascript alternative to CSS Counter?

Can a counter be implemented that changes the text of a tag directly using jQuery/Javascript? For example, if there were two tags like this: <a>hello</a> <a>bye</a> After executing the jQuery/JS function, the result would be: < ...

By using Yii2, you can pass an id to the URL by simply clicking on a

I am struggling with sending the post_id from a div containing text content (retrieved from a database) to a URL in order to render a view page displaying the entire content. I am using Yii2 and believe I need to use JavaScript for this task, but I am unsu ...

What is the best way to implement dragging functionality for an image within a specific area?

Here's a snippet of the code I'm working with: link This is the HTML code: <div class="border"> <div id="i-choose"> <input type="file" name="file" id="file" class="inputfile"> <label for="file"& ...

When trying to set the focus on the first item in a list using HTML and Angular, the focus unexpectedly shifts to the second

I've been tackling a UI requirement where the focus needs to be set on the first element of a list item constructed from an array of objects when the tab key is pressed for the first time. Subsequent tab key presses should cycle through the list items ...

Capturing numerous data points with JavaScript

<span> <label class="label">Color</label> <span class="foo"><input name="Color" value="Blue" class="customs" maxlength="100" type="text"/></span> </span> </span> <span> <label cla ...

What is the best method for designing a custom mask for the jQuery Masked Input Plugin that accommodates alphanumeric characters, spaces, and accented

Looking for a way to make a custom mask in jQuery Masked Input Plugin that allows alphanumeric characters, spaces, and accented characters? This is what I currently have: $.mask.definitions["A"] = "[a-zA-Z0-9 ]"; $("#input").mask("A?AAAAAAA"); However, ...

When using Node.js and geth together, running JavaScript code may lead to the creation of zombie processes, causing the

Currently, I am utilizing a JavaScript code that connects to the web3 package on Ethereum's JSON RPC API. This code is designed to iterate through each transaction in an incoming block. If the transaction involves an internal wallet, it sends the rele ...

Arrangement of cards in a column

As someone who is new to working with CSS, Wordpress, and similar technologies, I am seeking assistance. I am struggling with creating card layouts. My goal is to achieve a layout similar to this, where the cards are displayed in two columns instead of ju ...

Strange Actions with JQuery Drag-and-Drop Functionality

Apologies for my limited experience with JQuery UI, but I am in the process of creating a web-based chess engine for 2 players using JavaScript. Instead of point and click, I have decided to implement a user-friendly drag and drop feature for non-mobile us ...

Value as a String inside an Object

I am encountering an issue with using the obj to store string values in my project. The strings contain commas, and for some reason, it is not working as expected. const resizedUrl ={ 'mobile': "'images','400x/images' ...

Adding a JSON file to an Angular app hosted on a Grunt server

I'm currently following a beginner's guide for Angular and I need to incorporate a JSON file into my project. I started off by using Yeoman to set up my application, which is running on grunt. var phonecatApp = angular.module('phonecatApp& ...

How can we create responsive websites?

Since starting my Software Developer studies about 3 months ago, I've been working on a website project for a driving school with a team of four. The issue we're facing is that when we transfer and open files between laptops, the website layout a ...

Can I bypass an invalid SSL certificate when making a request using a JavaScript library?

Is it possible to bypass invalid SSL certificates when using the widely-used request library? You can find more information about the library here: https://www.npmjs.com/package/request I am currently integrating this library into a Node.js server to send ...

Error 404: Page not found. Sorry, we couldn't locate the Node JS and Express resource

I have been trying to access the routes /api and /api/superheroes, but I keep encountering an error message whenever I try. Not Found 404 NotFoundError: Not Found at C:\Users\mikae\Desktop\Project\node-express-swig-mongo\a ...