Max
Max

Reputation: 940

Highlighting table cells when clicked

I got this table. What I would like to do is when I click a cell it should be highlighted, and with a second click the highlight should be cleared. and the second problem is I would like to highlight several cells one by one keeping the previous highlights on. The fiddle is here:http://jsfiddle.net/2Lu3ss9g/

$(function() {
  $('td').click(function() {
    $(this).parents('table').find('td').each(function(index, element) {
      $(element).removeClass('on');
    });
    $(this).addClass('on');
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<table class="color_changing" border="1" cellpadding="15">
  <tbody>
    <tr>
      <td>23</td>
      <td>57</td>
      <td>62</td>
      <td>1162</td>
    </tr>
    <tr>
      <td>112</td>
      <td>5</td>
      <td>162</td>
      <td>88</td>
    </tr>
    <tr>
      <td>77</td>
      <td>62</td>
      <td>199</td>
      <td>211</td>
    </tr>
    <tr>
      <td>57</td>
      <td>64</td>
      <td>144</td>
      <td>9</td>
    </tr>

  </tbody>
</table>

Upvotes: 3

Views: 1866

Answers (1)

Bitwise Creative
Bitwise Creative

Reputation: 4105

Here's a simple solution using toggleClass:

$(function () {
    $('td').click(function () {
        $(this).toggleClass('highlight');
    });
});

Fiddle: http://jsfiddle.net/rqeec7r4/

Upvotes: 5

Related Questions