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

How can I extract the text within an element based on the position of the

In my current project, I have incorporated the incredibly useful jQuery TextRange plugin. Within a highlight div positioned above a textarea element, it is crucial for me to identify the specific element that the user is currently editing. To better illust ...

Preventing default action in jQuery to avoid interference with serialization and following AJAX request

I am encountering an issue with a php page that contains multiple forms, where I need jQuery to hide each form after the submit button is clicked, without refreshing the entire page. The unique challenge here is that the id's of these forms are dynami ...

Enhancing TypeScript builtin objects in Netbeans using a custom plugin

While in the process of converting JavaScript code to TypeScript, I encountered a challenge with extending built-in objects using Object.defineProperty, such as String.prototype. Object.defineProperty(String.prototype, 'testFunc', { value: funct ...

Creating a HTML5 canvas animation of an emoticon winking to add a fun touch to your

Currently, I am facing a challenge in animating an emoticon that was initially sketched on canvas. While following a tutorial to implement draw and clear animations using frames, I haven't been able to achieve the desired outcome. With 6 frames of the ...

How to automatically reset a form after submission in React using Ant Design?

When using the antd template for form design, I encountered an issue where form input values were not getting cleared after submission. I attempted to use this.props.form.resetFields(), but it resulted in the following error: Unhandled Rejection (TypeErro ...

Unable to apply ready function in jquery .load

When the document is ready, the following code is executed: jQuery(document).ready(function(){ jQuery('#button').click(function() { jQuery('#contact_form').load("/Users/mge/Downloads/jquery-ajax-1/readme.txt"); ...

Utilize JQuery to target all elements except for those within a specified excluded class

I am looking to target all elements within a container that has the class DnnModule-efforityEaloHTML var all = $(".DnnModule-efforityEaloHTML *") <== This method is effective However, I now want to exclude any items with the class nostrip I have atte ...

Keyframes and CSS Animation for Border Effects

I've been struggling to achieve a specific animation that I can't seem to get right. Despite searching online for solutions, none of them quite match the desired effect. What I'm looking for is a border animation that starts at the bottom l ...

Dynamically add a plugin to jQuery during execution

After installing jQuery and a jQuery-Plugin via npm, I am facing the challenge of using it within an ES6 module. The issue arises from the fact that the plugin documentation only provides instructions for a global installation through the script tag, which ...

Building a Sleek Hover Effect Dropdown Menu Using HTML and CSS

I've been following a tutorial on YouTube that showcases how to create a hoverable dropdown menu using HTML and CSS. The video link can be found below: Youtube Video Tutorial: https://www.youtube.com/watch?v=9Qrs8p7WgCc After replicating the code an ...

Customize the font color in Material UI to make it uniquely yours

How can I customize the default Text Color in my Material UI Theme? Using primary, secondary, and error settings are effective const styles = { a: 'red', b: 'green', ... }; createMuiTheme({ palette: { primary: { ...

The bxslider is displaying blank space when set to an infinite loop

I've incorporated a bxslider into my project using the following code: jquery: $(document).ready(function () { $('.bxslider').bxSlider({ minSlides: 2, maxSlides: 3, slideWidth: 340, mo ...

Issue with rendering JavaScript in Rails 3 caused by AJAX

Seeking help with implementing an AJAX request in a Rails (3.0.3) view using link_to. <%= link_to "like", toggle_author_likes_path(current_author, post), :remote => true %> The plan is for the LikesController#toggle action to render Javascript t ...

Using Vue.js 3 to fetch data from a REST API using the Axios

How do I properly retrieve and display an array using axios.get in Vue? The data is not showing up in my table cells when I use the v-for directive. Could the issue be related to the v-for statement? <tr v-for="params in form" :key=" ...

"Webpack error: Including a comma within a string leads to a syntax problem when bund

I'm attempting to merge this file into my main JS. var constants = { height: 600, width: 400, default_bezier = "[ { \"startPoint\" : [51.6503017608354,203.464445873753], \"endPoint\" : [-52.41285540263849,202.372456432 ...

Employing jQuery to send an ajax request by utilizing an anchor <a> tag

I'm attempting to use ajax to send content to a php script for database storage. My goal is to have a link on the page trigger this action, using jQuery. However, I've been struggling to create a functional function that can handle sending and re ...

Choose the AuthGuard category in real-time

My application intends to employ two distinct authentication strategies - one for users accessing via a browser and another for the public API. A specific header will be set for browser users, allowing my app to determine the appropriate auth strategy base ...

Enhancing link functionality with jQuery on a dynamically generated server page

I am facing an issue with my navigation menu that includes dropdowns. On desktop, the parent items need to be clickable as well, which is not a problem. However, for it to be responsive on mobile devices, I need to account for the lack of hover capability. ...

Instructions on how to dynamically show specific text within a reusable component by utilizing React and JavaScript

My goal is to conditionally display text in a reusable component using React and JavaScript. I have a Bar component that I use in multiple other components. In one particular ParentComponent, the requirement is to show limit/total instead of percentage va ...

encountering an issue while working with Selenium on Google Colab

I'm attempting to perform web scraping with selenium in Google Colab and running into some errors https://i.sstatic.net/egDf7.png The webpage is prompting me to enable JavaScript and disable any ad blockers. I tried enabling JavaScript by adding the ...