Issue with jquery .click function not triggering after CSS adjustment

In the process of creating a fun game where two players take turns drawing on a grid by clicking <td> elements. Currently, I have implemented the functionality to toggle the background color of a <td> element from black to white and vice versa with consecutive clicks. However, I'm facing an issue where after the first click, the third click doesn't trigger as expected.

$("td").click(function(){
    alert(0);
    alert($(this).css('background-color')); // alerts rgb(0, 0, 0)
    if($(this).css('background-color') == 'rgb(255, 255, 255)' || 'rgba(0,0,0,0)'){
        $(this).css('background-color', 'black');
        alert(1);
        var color = 'black';
    } else{
        alert(2);
        $(this).css('background-color', 'white');
        var color = 'white';
    }
    //alert(event.target.id);
    update( event.target.id, color);
});

The data reading function is working flawlessly

function read(){
    $.post("ajax.php",
        {
            read: '1',
        },
        function(data){
            values=data.split('*');
            //alert(values[1]);
            var id = '#' + values[0]+ '';
            //alert(id);
            $( id ).css('background-color', values[1]);
        }
    );
}

I have included an HTML table for the game's grid structure, generated dynamically through PHP. It's currently set as a 5x5 grid for simplicity.

<table>
    <tr>
        <td style="height: 21px; width: 21px; background-color:white;" id="a1"></td>
        <td style="height: 21px; width: 21px; background-color:white;" id="a2"></td>
        <td style="height: 21px; width: 21px; background-color:white;" id="a3"></td>
        <td style="height: 21px; width: 21px; background-color:white;" id="a4"></td>
        <td style="height: 21px; width: 21px; background-color:white;" id="a5"></td>
    </tr>
    <tr>
        <td style="height: 21px; width: 21px; background-color:white;" id="b1"></td>
        <td style="height: 21px; width: 21px; background-color:white;" id="b2"></td>
        <td style="height: 21px; width: 21px; background-color:white;" id="b3"></td>
        <td style="height: 21px; width: 21px; background-color:white;" id="b4"></td>
        <td style="height: 21px; width: 21px; background-color:white;" id="b5"></td>
    </tr>
    <tr>
        <td style="height: 21px; width: 21px; background-color:white;" id="c1"></td>
        <td style="height: 21px; width: 21px; background-color:white;" id="c2"></td>
        <td style="height: 21px; width: 21px; background-color:white;" id="c3"></td>
        <td style="height: 21px; width: 21px; background-color:white;" id="c4"></td>
        <td style="height: 21px; width: 21px; background-color:white;" id="c5"></td>
    </tr>
    <tr>
        <td style="height: 21px; width: 21px; background-color:white;" id="d1"></td>
        <td style="height: 21px; width: 21px; background-color:white;" id="d2"></td>
        <td style="height: 21px; width: 21px; background-color:white;" id="d3"></td>
        <td style="height: 21px; width: 21px; background-color:white;" id="d4"></td>
        <td style="height: 21px; width: 21px; background-color:white;" id="d5"></td>
    </tr>
    <tr>
        <td style="height: 21px; width: 21px; background-color:white;" id="e1"></td>
        <td style="height: 21px; width: 21px; background-color:white;" id="e2"></td>
        <td style="height: 21px; width: 21px; background-color:white;" id="e3"></td>
        <td style="height: 21px; width: 21px; background-color:white;" id="e4"></td>
        <td style="height: 21px; width: 21px; background-color:white;" id="e5"></td>
    </tr>
</table>

Would greatly appreciate any assistance provided. Thank you

Answer №1

If you're looking for guidance, I suggest the following approach:

Cascading Style Sheets (CSS)

.black {
  background-color: black;
}
.white {
  background-color: white;
}

JavaScript

$("td").click(function(event) {
  alert(0);
  alert($(this).hasClass("black") ? "Black" : "White"); // alerts rgb(0, 0, 0)
  if ($(this).hasClass("white")) {
    $(this).removeClass("white").addClass("black");
    alert(1);
    var color = 'black';
  } else {
    alert(2);
    $(this).removeClass("black").addClass("white");
    var color = 'white';
  }
  update(event.target.id, color);
});

When dealing with AJAX requests:

function read() {
  $.post("ajax.php", {
      read: '1',
    },
    function(data) {
      values = data.split('*');
      $.each(values, function(k, v) {
        $("#" + v[0]).toggleClass("black white");
      });
    }
  );
}

Consider this alternative option suggested by @KevinB:

$("td").click(function(event) {
  $(this).toggleClass("black white");
  color = $(this).hasClass("black") ? "black" : "white";
  update(event.target.id, color);
});

Update

To see a working example in HTML code, visit: https://jsfiddle.net/Twisty/7tnpm90j/

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

Minimizing code with JQuery

Looking for a way to consolidate this code into a single function without repeating it multiple times. I struggle with coding but know there must be a solution out there. Any guidance would be greatly appreciated. (function() { $('.one').cli ...

Steps to activate overflow on `react-bootstrap` NavDropdown

I'm having a bit of trouble with using react-bootstrap's NavDropdown in my NavBar to display a list of data. Sometimes, the list extends beyond the view and gets cut off at the bottom. I want to add overflow: auto to the list to make it scrollabl ...

A tutorial on utilizing a bundle in webpack based on certain conditions

My project consists of an app.bundle.js (the main app bundle) and two cordova bundles: iosCordova.bundle.js and androidCordova.bundle.js. Depending on whether the user is logging in on an iOS or Android device, I only script src one of them. All the bundle ...

Troubleshooting: JQuery - Applying CSS to dynamically generated elements

I used JQuery to dynamically generate a table, but I'm having trouble applying CSS to the columns. You can see an example at this Codepen link here. Specifically, I need to set the width of the first column to 100px. Could someone please assist me wi ...

What is the best way to reorganize an object's properties?

Looking for a way to rearrange the properties of an existing object? Here's an example: user = { 'a': 0, 'b': 1, 'c': 3, 'd': 4 } In this case, we want to rearrange it to look like this: user = { &a ...

Looking to execute a wp_query in a different PHP file for handling an AJAX request

However, it indicates: Severe error: The class 'WP_Query' cannot be located in C:\wamp64\www\word\wp-content\themes\word\templates\calendar-function.php on line 67. ...

What's the best way to transform createHmac function from Node.js to C#?

Here's a snippet of code in Node.js: const crypto = require('crypto') const token = crypto.createHmac('sha1', 'value'+'secretValue').update('value').digest('hex'); I am trying to convert t ...

Coding in PHP, JavaScript, and HTML allows builders

I am facing some difficulties in locating my specific question, so I will describe it here. Currently, I am working with an oracle database and integrating it into an HTML website using javascript and php. I have successfully displayed the php file, but th ...

Upon the initial data retrieval, everything seems to be working fine. However, when the user transitions to chatting with another user, the state value does not reset and instead shows a combination

Exploring the world of react.js and node.js, I am currently working on developing a chatting application with the integration of socket.io. The issue I'm facing is that when a user clicks on another user to chat, the previous chat messages are display ...

Loading parts of a web page dynamically with ajax or jquery techniques

I've been working on a video portal website and it's almost complete, but I'm experiencing some performance issues. The page takes too long to load the entire content. My goal is to have the header of the page load immediately and then use ...

What is the reason behind this occurrence with just one 's'?

I'm currently encountering an issue with my HTML form field. Here is the code snippet: <div style="width:100px; padding-top:10px;margin-left:10px;float:left;" align="left">Your Username:</div> <div style="width:300px;float:left;" align ...

What is the most efficient method for adding each unique unordered list element with a specific class to the nearest parent article tag

The current code structure looks like this: <article id="post-529"></article> <ul class="post-meta"></ul> <article id="post-530"></article> <ul class="post-meta"></ul> <article id="post-531"></a ...

Trouble displaying JSON data with AngularJS $http service

Struggling to retrieve json data. Initially, I created an ajax request that functioned properly in a regular html page but failed in my angular app. As a result, I decided to experiment with the built-in $http get function. Surprisingly, no errors are thro ...

stacking order of floated and positioned elements

After researching on MDN and reading through this insightful blog post, it is suggested that in the absence of a z-index, positioned elements are supposed to stack above float elements when they overlap. However, upon closer examination, the example prov ...

The command "Npm Start Causes sleep is not accepted" just popped up

After cloning a React project from GitHub, I proceeded to run npm install, which successfully installed the node_modules folder. However, upon trying to run npm start, I encountered the following error: 'sleep' is not recognized as an internal or ...

What causes certain divs to protrude when the parent div has overflow:hidden property enabled?

Issue: I am facing difficulty aligning all elements within one div without any overflow issues. Even with the parent div set to overflow:hidden, some child divs are protruding out of the container. How can I resolve this problem? Example: http://jsfiddle. ...

The custom validator in Material2 Datepicker successfully returns a date object instead of a string

Im currently working on developing a unique custom validator for the datepicker feature within a reactive form group. Within my code file, specifically the .ts file: form: FormGroup; constructor( private fb: FormBuilder, ...

Locate the element within the specified parameters using [protractor]

Here's my query: element.all(by.repeater('user in users')).then(function(rows) { // looking to locate an element in rows using CSS selector, for example } UPDATE : I want to clarify that I am trying to find an element using rows[rows.len ...

Generating an order prior to payment being made by the customer

When a user selects a product and clicks the pay button, they are redirected to Stripe where a new order is created. However, if the user changes their mind and cancels the payment during the Stripe checkout process, the order has already been created. How ...

Can you navigate between slides with JQuery?

Looking to create a website similar to . The only obstacle I am encountering is understanding the code. I prefer using JQuery over MooTools. Is there anyone who can kindly assist me by providing a demo? I want to implement the functionality of switching b ...