Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple JavaScript chess board

Could anyone give me a hint on how to generate a chess board (8x8) using JavaScript, using a table tags or ?

I've got the following so far:

<DOCTYPE html>
<html>
<head>
<style>

div
{
border:1px solid black;
width:20px;
height:20px;
}

</style>
</head>
<body>
<script type="text/javascript">

    // create a chess table 8x8.

    var count = 0;

while (count < 64)
    {

    if (count % 2 == 0)

        {

        if (count % 8 == 0 && count !=0)
            {
            document.write('<br/><div style="background-color:#000000;float:left;">&nbsp</div>');

            }
        else    
            {
            document.write('<div style="background-color:#000000;float:left;">&nbsp</div>');    
            }
        }

    else

        {
        document.write('<div style="background-color:#FFFFFF;float:left;">&nbsp</div>');
        }
    /*  
    */          
    count++;
    }
</script>

</body>
</html>

I tried to assign black and white to each odd and even number respectively, but it doesn't work this way.

Thank you in advance.

like image 987
Tyrant Avatar asked May 22 '13 05:05

Tyrant


2 Answers

I can not test it at this moment but this should work. This code creates a 8x8 table in which black cells are tagged with "black" class and white cells are tagged with "white" class. Use CSS to give them color. I hope it helps.

var table = document.createElement("table");
for (var i = 1; i < 9; i++) {
    var tr = document.createElement('tr');
    for (var j = 1; j < 9; j++) {
        var td = document.createElement('td');
        if (i%2 == j%2) {
            td.className = "white";
        } else {
            td.className = "black";
        }
        tr.appendChild(td);
    }
    table.appendChild(tr);
}
document.body.appendChild(table);
like image 149
Alfonso Jiménez Avatar answered Oct 12 '22 13:10

Alfonso Jiménez


At some point for me, this became code golf:

http://jsfiddle.net/4Ap4M/

JS:

for (var i=0; i< 64; i++){
    document.getElementById("mainChessBoard").appendChild(document.createElement("div")).style.backgroundColor = parseInt((i / 8) + i) % 2 == 0 ? '#ababab' : 'white';    
}

HTML:

<div id="mainChessBoard">
</div>

CSS:

#mainChessBoard
{
    width:160px;
    height:160px;
    border:1px solid black;
}

div
{
 width:20px;
 height:20px;
 float:left;
}
like image 24
aquinas Avatar answered Oct 12 '22 12:10

aquinas