Interact with the cells in the table by clicking on them and managing class modifications for

Table structure:

<table class="ui celled table unstackable" id="tblHits">
        <thead>
            <tr>
                <th>40</th>
                <th>40</th>
                <th>40</th>
                <th>25</th>
                <th>15</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td class="addNone" id="t01">01</td>
                <td class="addNone" id="t02">02</td>
                <td class="addNone" id="t03">03</td>
                <td class="addNone" id="t04">04</td>
                <td class="addNone" id="t05">05</td>
            </tr>
        </tbody>
    </table>

Issue with clicking and changing classes:

$("#tblHits:has(td)").click(function(e) {
    var clickedCell= $(e.target).closest("td");
    if ( $('#t'+ clickedCell.text() + '').hasClass( "addNone" )) {
         $("#tblHits td").removeClass("addNone");
         $('#t'+ clickedCell.text() + '').addClass("addHit");
         alert('Clicked table cell value is: <b> ' + clickedCell.text());
    }
    else if ( $('#t'+ clickedCell.text() + '').hasClass( "addHit" )) {

         $("#tblHits td").removeClass("addHit");
         $('#t'+ clickedCell.text() + '').addClass("addMiss");
         alert('Clicked table cell value is: <b> ' + clickedCell.text());
     }
     else if ( $('#t'+ clickedCell.text() + '').hasClass( "addMiss" )) {
         $("#tblHits td").removeClass("addMiss");
         $('#t'+ clickedCell.text() + '').addClass("addNone");
         alert('Clicked table cell value is: <b> ' + clickedCell.text());
     });

Your input on resolving this issue is appreciated. Thank you!

Answer №1

Implement "event delegation" to capture clicks on a parent element (similar to how you listened for clicks on the table). However, retrieving the clicked cell appears to be problematic.

Simply verify if the clicked element is the desired td, and proceed accordingly. This approach not only enhances performance by allowing early script termination for uninteresting clicks, but also streamlines the logic.

$('#tblHits').on('click', function (evt) {
    var $td = $(evt.target);
    if (!$td.is('td')) return;

    if ($td.hasClass('addNone')) {
       $td.removeClass('addNone').addClass('addHit');
    } else
    if ($td.hasClass('addHit')) {
       $td.removeClass('addHit').addClass('addMiss');
    } else
    if ($td.hasClass('addMiss')) {
       $td.removeClass('addMiss').addClass('addNone');
    }
});

Check out this fiddle: https://jsfiddle.net/bkry0txr/4/

Additionally, it's recommended to introduce another class name to the td selection, like so:

<tr>
  <td class="hitbox addNone"></td>
  <td class="hitbox addHit"></td>
  <!-- etc -->
</tr>

Subsequently in the JS:

$('#tblHits').on('click', function (evt) {
    var $td = $(evt.target);
    if (!$td.is('.hitbox')) return;
    // etc..
});

This method allows for flexibility with other td elements or alternative elements. As long as the desired element retains the 'hitbox' classname, the JS functionality remains unchanged.

Answer №2

To add interactivity to your table cells, you can set up a click event listener for each td. Then, based on the current CSS class of the clicked cell, you can modify its styling accordingly.

Avoid using the selector $('#t'+ clickedCell.text()) as it is unnecessary in this scenario.

$( "td" ).each(function(index) {
  $(this).on("click", function(){

    if ($(this).hasClass('addNone')) {
       $(this).removeClass('addNone').addClass('addHit');
    } else if ($(this).hasClass('addHit')) {
       $(this).removeClass('addHit').addClass('addMiss');
    } else if ($(this).hasClass('addMiss')) {
       $(this).removeClass('addMiss').addClass('addNone');
    }

  });
});

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

Constantly encountering errors instead of obtaining results with each AJAX call

I have a button on my webpage that triggers a JavaScript function I've created. I have successfully debugged into this function. However, whenever the function reaches the AJAX part, it always returns with an error message alert. I aim for the AJAX ...

A step-by-step guide on setting --max-old-space-size using the npm link command

Can the --max-old-space-size parameter be configured using npm link? I am aware that it can be set using the node command such as node --max-old-space-size=, but I am attempting to achieve the same result through the npm link command. Is this feasible? Yo ...

How does the max() function in JavaScript handle arrays when there are multiple numbers of the same maximum value?

Assuming we have the following scenario: array=[5,5,5,5,3,2]; return Math.max.Apply(Math,array); How can I modify the code to output the numbers in sequential order from first to last? ...

Is there a method to pre-load a CSS background image so that it can still be displayed even without an internet connection?

Situation: Imagine having a web app that shows an error message when trying to perform an action but fails due to a connectivity problem. The error dialogue has a CSS class with a background image that can't load because of the connection issue, res ...

Analyzing an HTTP response containing a Content-Type header specifying image/jpeg

Currently, I am developing my first web application and the task at hand involves loading an image from a database and sending it to the client for display. On the server side, I have the following code: res.setHeader('Content-Type', pic.mimetyp ...

Using `v-if` with a Vuex getter

Currently, I am utilizing a vuex getters called isLoggedIn to verify whether a user is logged in or not. <div v-if="isLoggedIn" class="ml-2 py-2 group relative">...</div> data() { return { isLoggedIn: this.$store. ...

Utilizing RSelenium for accessing a website built using the <td> element

My supervisor has tasked me with retrieving data from the China in-depth accident study database. Given my limited experience with HTML and javascript, I decided to utilize RSelenium and phantomjs to assist me in completing this task. Although I was able ...

The image is failing to animate according to the PNG sequence function

Enhanced Functionality: Upon clicking the "Tap Here" image button, a function called "GameStart()" is triggered. This function ensures that the main image "Star" descends down the page from the top through an animated sequence using png logic. The propose ...

Is there a way to design a form that appears as though it's levitating above a div element?

I am new to web development and currently practicing by converting PSD designs into HTML pages. I am facing an issue where I need to create a form that appears to be floating on top of a div, with the form being taller than the div itself. Here is an illu ...

Seeking assistance with printing an HTML template using a printer in Angular 2. Can anyone provide guidance on how

I have a scenario where I need to print an HTML template from within my Angular 2 component. Specifically, I want to be able to click on a print button on the same page and trigger the print function, which would display a print preview and allow the use ...

Creating fixed or absolute position tooltips for iPhones and iPads: A step-by-step guide

I've been enjoying using the qTip jQuery plugin for some time now and haven't experienced any issues. However, I recently noticed a bug with the tooltips on iPads and iPhones. Here are the symptoms I've observed: Everything works fine unt ...

From vanilla JavaScript to the powerful lodash library

Can you help me determine if these statements are equivalent? myApp.filter('myFilter', function() { var result, i, sport, y, contains, league; return function(sports, filterBy) { if (angular.isUndefined(sports) || !filterBy) { ...

Is it considered a best practice in React to modify styles of elements using the className state?

I have a unique component that can showcase either an error message or a success message. These are the only two possible "states" it can be in, so the styling is limited to either of these options: for success: background-color: green; for error: backgro ...

Retrieve the background color using code-behind

Despite its humorous appearance, I am having trouble with the Syntax :( I have a background color in my code behind file and need to correct the syntax here so that my Table displays the correct background color: <Table style="background-color:" &apos ...

How can I trigger an event in Vue.js when a selection is made in a dropdown menu?

Here is an illustration fiddle: https://jsfiddle.net/40fxcuqd/ Initially, it shows the name "Carl" If I choose Carol, Clara, etc., an event will be triggered and data will be logged to the console. However, if I click on the dropdown and select "Carl" ...

What is the best way to effectively clear memory in THREE.js?

After successfully rendering the model, rotating and zooming work perfectly. However, when attempting to clear the scene by clicking the button#clear, issues arise. The expectation is to traverse through the scene, add its children to an array, iterate ov ...

Is there a way to automatically display the first highlighted fragment in reveal.js?

Is it possible to have the first fragment automatically visible in reveal.js? I am utilizing the text colour highlight feature in reveal.js to make the most recent fragment appear with a slightly brighter color, drawing attention to that specific section. ...

Toggling checkboxes based on user input

My dynamic table is filled with checkboxes that can be checked or unchecked. I have created a jquery script that should change the background color of the table cell whenever a checkbox is modified. However, the script seems to have some bugs and doesn&apo ...

Incorporate a captivating background image into your SVG design

Currently working with Snap.svg, my aim is to include a background image on a polygon shape. The specific polygon in question is outlined as follows: <svg id="test" height="600" width="600" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink= ...

Searching for a key and swapping it with a corresponding value in JavaScript or Node.js

let data = [...]; I am attempting to merge two object datasets into one output, focusing on those with links labeled as "Asset." In my current implementation, when dealing with arrays such as mediaFile, only a single entry is being displayed instead of m ...