Changing color of cell at specific 'coordinate'

Suhan Gui

I have a table with cells they are each 'labeled' with a coordinate by [row,column]. For example, the first cell is [0,0]. I want a specific coordinate of the table to change color. I can get it to change color by clicking on it right now.

There should be a variable that is equal to an array. Let's say [2,2] for example. The cell at [2,2] should turn to a different color.

Code I have so far:

function generateGrid( rows, cols ) {
    var grid = "<table>";
    for ( row = 1; row <= rows; row++ ) {
        grid += "<tr>"; 
        for ( col = 1; col <= cols; col++ ) {      
            grid += "<td></td>";
        }
        grid += "</tr>"; 
    }
    return grid;
}

$( "#tableContainer" ).append( generateGrid( 5, 5) );

$( "td" ).click(function() {
    var index = $( "td" ).index( this );
    var row = Math.floor( ( index ) / 5) + 1;
    var col = ( index % 5 ) + 1;
    var coord= [row,col]
    $( "span" ).text( "Coordinate: " + coord );
    $( this ).css( 'background-color', 'red' );
    //just create a new variable equal to an array. For ex: var place=[2,2] and make the cell at [2,2] turn red.
});
td {
    width: 50px;
    height: 50px;
}

td{
  border:1px solid black;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span>Select a cell!</span>
<div id="tableContainer"></div>

stldoug

If you need to specify a certain matrix, you can use jQuery's eq() selector, like so:

$("tr:eq(2) td:eq(2)").css( 'background-color', 'red' );

function generateGrid( rows, cols ) {
    var grid = "<table>";
    for ( row = 1; row <= rows; row++ ) {
        grid += "<tr>"; 
        for ( col = 1; col <= cols; col++ ) {      
            grid += "<td></td>";
        }
        grid += "</tr>"; 
    }
    return grid;
}

$( "#tableContainer" ).append( generateGrid( 5, 5) );

$("tr:eq(2) td:eq(2)").css( 'background-color', 'red' );
td {
    width: 50px;
    height: 50px;
}

td{
  border:1px solid black;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span>Cell [2,2] automatically changed!</span>
<div id="tableContainer"></div>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related