Search code examples
javascriptjqueryhtmlcss

How can I change background color for table cells always when clicked?


For example: You have a table, and it has 4 tds and 2 trs. Table's background color is white. If I click to A td, A td should be red, than if I click to B, B td should be red and A td should be red too. If I click to C than, C should be red and B and A should be red too.

I have something like this. But it isn't good, because when I click again I want to change color back to white.

http://jsfiddle.net/k8UgT/193/

The code i use

$(function() {
  $('td').click(function() {
    $(this).css('background', '#aaa')
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<table>
  <tr>
    <td onclick="function()">AAA</td>
    <td onclick="function()">BBB</td>
    <td onclick="function()">CCC</td>
  </tr>
  <tr>
    <td onclick="function()">DDD</td>
    <td onclick="function()">EEE</td>
    <td onclick="function()">FFF</td>
  </tr>
</table>


Solution

  • First of all you don't need to onclick attribute on the td elements. Second of all I would suggest using a CSS class instead of setting the background color.

    CSS

    .red-cell {
       background: #F00; /* Or some other color */
    }
    

    JS

    $( function() {
      $('td').click( function() {
        $(this).toggleClass("red-cell");
      } );
    } );
    

    Read more about toggleClass here. Updated fiddle