Dan Duca Dan Duca - 4 months ago 13
Javascript Question

Table 5 rows and 5 columns in which the cell in the middle color on click

I'm beginner and I have a project in which i must to do a table, 5 rows, 5 columns. The cell in the middle (x=3, y=3), on click must color red, and then move this cell in the table without using mouse, only from arrows keys in the keyboard.



<style type="text/css">
td
{
width: 50px;
text-align:center;
background-color:blue;
}
</style>
<script
src="http://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
<script>
$( function() {
$('td').click( function() {
$(this).css('background', 'red')
} );
} );
</script>
<table border="1">
<tr>
<td >-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
</tr>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
</tr>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
</tr>
</table>




Answer Source

Based on the comment, what is requiered is to change the color of the middle cell (x=3, y=3), so we need to add an id to your middle cell:

...
<tr>
    <td>-</td>
    <td>-</td>
    <td id="middle-cell">-</td>
    <td>-</td>
    <td>-</td>
</tr>
...

And then change your function to select it:

<script>
$( function() {
  $("#middle-cell").click( function() {
    $("#middle-cell").css('background', 'red')
  } );
} );
</script>