What is the best way to design a table to allow for changing the colors of specific boxes in the table when clicked?

I am looking to create a feature where the elements in this table change color from the background color to red and back to the default color when they are clicked. Can anyone help me achieve this?

<table align="center" style="height: 355px;" width="664" border="3px">
  <tbody>
    <tr>
      <td style="width: 94px;">25</td>
      <td style="width: 94px;">26</td>
      <td style="width: 95px;">27</td>
      <td style="width: 95px;">28</td>
      <td style="width: 95px;">29</td>
      <td style="width: 95px;">30</td>
      <td style="width: 95px;">&nbsp;</td>
    </tr>
  </tbody>
</table>

Answer №1

To add an onclick listener to dynamically generated cells, you can do the following:

<table align="center" style="height: 355px;" width="664" border="3px">
      <tbody>
        <tr>
          <td style="width: 94px;" onclick="changeColor(this)">25</td>
          <td style="width: 94px;">26</td>
          <td style="width: 95px;">27</td>
          <td style="width: 95px;">28</td>
          <td style="width: 95px;">29</td>
          <td style="width: 95px;">30</td>
          <td style="width: 95px;">&nbsp;</td>
        </tr>
      </tbody>
    </table>

In jQuery (or alternatively in JavaScript), you would use a function like this:

function changeColor(elt){
  $elt = $(elt);
  $elt.toggleClass("redBg");
}

You can define the styling for the "redBg" class in CSS file as follows:

.redBg {
  background-color: red;
}

Answer №2

Feel free to experiment with the classes by adding and removing them as needed. You can also customize the style further using this method.

$(document).ready(function() {
  $('.table tbody tr td').on('click', changeColor);
});

function changeColor() {
 if(!this.classList.contains('first')){
  this.classList.add('first');
  this.classList.remove('second');
 } else {
 this.classList.remove('first');
 this.classList.add('second');
 }
}
.first{
  background : red;
}
.second{
  background : blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table align="center" class="table" style="height: 355px;" width="664" border="3px">
  <tbody>
    <tr>
      <td style="width: 94px;">25</td>
      <td style="width: 94px;">26</td>
      <td style="width: 95px;">27</td>
      <td style="width: 95px;">28</td>
      <td style="width: 95px;">29</td>
      <td style="width: 95px;">30</td>
      <td style="width: 95px;">&nbsp;</td>
    </tr>
  </tbody>
</table>

Answer №3

To easily toggle the class, you can use classList.toggle('class')

document.querySelectorAll('tr td').forEach(function(a){
a.addEventListener('click',function(){
this.classList.toggle('color')
})
})
.color{
background-color:red;
}
<table align="center" style="height: 355px;" width="664" border="3px">
  <tbody>
    <tr>
      <td style="width: 94px;">25</td>
      <td style="width: 94px;">26</td>
      <td style="width: 95px;">27</td>
      <td style="width: 95px;">28</td>
      <td style="width: 95px;">29</td>
      <td style="width: 95px;">30</td>
      <td style="width: 95px;">&nbsp;</td>
    </tr>
  </tbody>
</table>

Answer №4

You might want to consider adding a attribute like data-color=true and then simply apply the color change

var tableData = document.getElementsByTagName("td"),
    totalDataElements = tableData.length,
    index;
function adjustColor(){
  var colorChange = this.style.background!="blue";
  this.style.background = (colorChange?"blue":"initial");
}
for(index=0;index<totalDataElements;index+=1){
  if(tableData[index].getAttribute("data-color")=="true"){
    tableData[index].onclick = adjustColor;
  }
}
<table align="center" style="height: 355px;" width="664" border="3px">
  <tbody>
    <tr>
      <td style="width: 94px;" data-color="true">25</td>
      <td style="width: 94px;" data-color="true">26</td>
      <td style="width: 95px;">27</td>
      <td style="width: 95px;" data-color="true">28</td>
      <td style="width: 95px;">29</td>
      <td style="width: 95px;" data-color="true">30</td>
      <td style="width: 95px;">&nbsp;</td>
    </tr>
  </tbody>
</table>

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

Having trouble with Bootstrap 4: I want to rotate an image, but every time I try, it ends up overwriting the CSS properties

I am currently working on a website using bootstrap 4, and I'm facing an issue with the image I selected. It seems to rotate to the right and is not displaying correctly. click here for image preview The main problem lies in rotating the image witho ...

The error message "THREE is not defined" indicates a problem

Hey there! I've been experimenting with running some three.js examples on my local machine. I ran into some security issues, so I set up a local server using Python. While the background image and text appear as expected, the animations are not workin ...

``Next.js allows you to nest components within a component to create routing functionalities

My login page has 3 different roles for logging in: Admin, Student, and Company. Instead of redesigning the entire page, I just want to update the login component for each specific role. Login Page export default function Authpage(){ return( ...

Feeling trapped by the NullPointer Exception bug

I am currently automating the add to cart process on the website "http://www.oyehappy.com" using TestNG POM Structure. I have encountered a NullPointer Exception while handling autosuggestion. The code for my POM Class is as follows: public class productPa ...

Is an Object in Javascript an Array of Elements?

Today, I am facing a challenge. I have an HTML Form that can contain a variable number of HTML Input Fields for email addresses. I am using Javascript to process this data and to post it via XMLHttpRequest. To fetch the input fields, I use the following c ...

Ways to extract data from a chosen radio button choice

Excuse me, I have a form with an input field and radio buttons. Can someone please help me with how to retrieve the value of the selected radio button and then populate that value into the input text field? For reference, here is the link to the jsfiddle: ...

Tackling the sticky header problem with in-browser anchoring and CSS dynamic height restrictions

I am experimenting with a unique combination of a Pure CSS in-page anchoring solution using scroll-behavior: smooth and scroll-margin-top settings, along with a sticky header for in-page navigation. By utilizing IntersectionObserver, I can identify when t ...

Display the names of files depending on the selection made in the drop-down menu

In order to utilize a value from a select box for a PHP function later on the page, I am seeking assistance. Within my index.php file, there is a standard select drop down containing folder names as values and options. After selecting a folder, I aim to e ...

A dynamic and versatile solution for achieving uniform column heights across different web browsers using child elements

Get straight to the point. I'm looking for a solution to create a responsive two-column layout like the one shown in the image below. https://i.sstatic.net/mHhfc.png The width ratio of the .left and .right columns should always be 75/25% relative t ...

How can I effectively retrieve the JWT in a node environment?

I've successfully set up JWT authentication using Node.js. After the user signs in, Node.js generates a JWT and sends it back to be stored in the localStorage. However, I've encountered an issue when trying to access this token within the express ...

What is the best way to conceal a menu that automatically scrolls to the content when it is clicked?

Below is a Codepen with a menu that isn't behaving as expected. var menu = document.querySelector('.nav__list'); var burger = document.querySelector('.burger'); var doc = $(document); var l = $('.scrolly'); var panel = $ ...

Update the gulp watch function to use gulp@4

We are currently in the process of transitioning from <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fb9c8e978bbbc8d5c2d5ca">[email protected]</a> to gulp@4, and encountering difficulties during the switch. Upon r ...

- Bullet point: Table heading alignment variation

When it comes to centering a <th> element inside an <li>, different browsers have different approaches. In Internet Explorer, Edge, and Safari, the <th> is center-justified. However, in Chrome, Firefox, and Opera, it's left-justifie ...

How can I create numerous HTML containers using Javascript?

I've been learning from this tutorial: Instead of just displaying the last database object, I want to display all of them. I have tried outputting the database contents and it's working fine. Now, I just need to adjust the HTML. I attempted to ...

Ways to disable HTML loading prior to CSS loading

After downloading a site template, I observed that the HTML is loaded first before the CSS. Is there a way to disable this? I am looking to create a preloader for the website. ...

Displaying JSON data from the API on a webpage within a NodeJS weather application

Currently, I am in the process of developing a weather application using NodeJS. I have successfully retrieved JSON formatted data from the weather site's API. Nonetheless, I am perplexed about how to transmit this data to the application. Below is a ...

JavaScript code for displaying mouse positions and Geolocation using OpenLayers, along with a Geocodezip demonstration

I have attempted to merge Geolocation and Mouse Position Display (longitude/latitude; outside of map) from the OpenLayers and geocodezip site, but I am facing issues. The Mouse Position Display works correctly, however, Geolocation does not seem to work. U ...

Merge the throw new Error statement with await in a single expression

Is it possible to combine throwing an error and using the await keyword in one statement using the AND operator? The code snippet below demonstrates my intention: throw new Error() && await client.end(). So far, this approach has been working wel ...

The Webix component is experiencing a lack of refreshment

function refresh_group_items(){ //console.log("calling1"); window.setTimeout(function(){ $$("cfg").reconstruct() }, 3000); } $.ajax({ type: "POST", xhrFields:{ withCredentials: true }, beforeSend: function(reque ...

Encountered an issue while trying to install using the command npm install react router dom

For a project I'm working on, every time I attempt to use this command, an error message appears and the installation fails. I've tried multiple commands with no success. Here is the specific error message: npm ERR! code 1 npm ERR! path C:\ ...