Suhan Gui Suhan Gui - 27 days ago 9
CSS Question

Preventing cells which have changed colors from changing colors again

I want to create a sort-of clickable grid. Whenever I click on a blank cell, it should change to either black or white. The next cell that I click should be the other color (if the first cell I click is white, the next cell I click should be black and vice versa). I got this done but if I have clicked on a cell already, it changes the color again which should not happen.

This is the code I have so far:

HTML:

<html>
<head>
<link type="text/css" rel="stylesheet" href="stylesheet.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<title>Tic-Tac-Toe Pro</title>
</head>
<body>
<div id="tableContainer"></div>
<script type='text/javascript' src='app.js'></script>
</body>
</html>


Js & jQuery:

var white=true;
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;
if (white==true){
$( this ).css( 'background-color', 'white' );
white=false
}
else if (white==false){
$( this ).css( 'background-color', 'black' );
white=true;
}
});


CSS:

html{
background-color:blue;
}
td {
border: 1px solid;
width: 25px;
height: 25px;
}

table {
border-collapse: collapse;
}

Answer

You need to keep track of whether the element has been clicked. One way to do this is using .data():

$("td").click(function() {
    var $td = $(this);
    if ($td.data('clicked')) 
        return;

    $td.data('clicked', true);

    $td.css('background-color', white ? 'white' : 'black');
    white = !white;

});
Comments