8

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.

Free Consulting
  • 4,141
  • 1
  • 25
  • 48
Tyrant
  • 97
  • 1
  • 1
  • 7
  • 1
    Out of interest why do you want to do this with javascript instead of just manually writing out the html? – Chris Moutray May 22 '13 at 05:23
  • any chance your using opengl? if so check out http://www.java-tips.org/other-api-tips/jogl/another-method-of-texture-mapping-a-checkerboard-image-onto-two-recta.html very easy with opengl – Glen Morse May 22 '13 at 05:23
  • Also you might want to look at html5 canvas – Chris Moutray May 22 '13 at 05:24
  • 1
    @GlenMorse This is JavaScript not Java – Chris Moutray May 22 '13 at 05:25
  • @Chirs Moutray could still use webgl it would still work...and checkerboards are one of the basic in gl. – Glen Morse May 22 '13 at 05:28
  • @GlenMorse Creating a few divs vs importing and learning to use WebGL and then drawing 3D primitives? Your suggestion of WebGL is total overkill. – doppelgreener May 22 '13 at 05:29
  • 1
    Hi all, thanks for the suggestions so far. I am still learning and my assignment is to do this with JavaScript exclusively. *my original post should read "... table tags or div". – Tyrant May 22 '13 at 05:30
  • http://code.google.com/p/o3d/source/browse/trunk/samples_webgl/shaders/checker-glsl.shader?r=219 quick and easy if your wanting checkerboard.. Thats why i asked if he was using gl.. – Glen Morse May 22 '13 at 05:30

10 Answers10

16

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);
Alfonso Jiménez
  • 1,159
  • 1
  • 12
  • 24
15

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;
}
aquinas
  • 21,814
  • 5
  • 51
  • 78
  • really appreciate the answer, but the right bottom or left top square has to be white square in a chess board (so flipping the colors, would do) – David Gladson Jan 13 '21 at 18:56
3

This is the basic foundation to build your chess board.
You can check out the chess board pattern in the console.

   var chessBoard = function(size){
    var hash = '#'
    var space = '_'
    for (var i = 0; i < size; i++) 
    {        

        hash += '\n'

        for (var j = 0; j < size; j++) 
        {
        if((i +j) % 2 == 0)
        {
        hash  += space
        }
        else
        {
        hash  += "#"
        }
    };

};

console.log(hash)
}(8)
user3449311
  • 167
  • 1
  • 5
2

You can generate boards of any size you want, and this way is pretty easy to change the size of the squares and the colors. you don't need to change anything else.

It is good practice to keep appearance on the stylesheet. Also don't use document.write

http://jsfiddle.net/YEJ9A/1/

Javascript

var x=8;
var y=8;

var chessBoard = document.getElementById("chessBoard");

for (var i=0; i<y; i++){
    var row = chessBoard.appendChild(document.createElement("div"));
    for (var j=0; j<x; j++){
        row.appendChild(document.createElement("span"));
    }
}

CSS

#chessBoard span{
    display: inline-block;
    width: 32px;
    height: 32px;
}

#chessBoard div:nth-child(odd) span:nth-child(even),
#chessBoard div:nth-child(even) span:nth-child(odd){
    background-color: black;
}
#chessBoard div:nth-child(even) span:nth-child(even),
#chessBoard div:nth-child(odd) span:nth-child(odd){
    background-color: silver;
}
Community
  • 1
  • 1
Vitim.us
  • 16,145
  • 12
  • 81
  • 96
2

May be you want to do it with divs, not with the table. So here is the solution for it.

$(document).ready(function() {
  for (var i = 1; i <= 8; i++) {
    var divRow = $("<div>", {
      class: "row",
    });
    for (var j = 1; j <= 8; j++) {
      var div = $("<div>", {
        class: "square"
      });

      if (i % 2 == j % 2) {
        $(div).addClass("white");
      } else {
        $(div).addClass("black");
      }
      divRow.append(div);
    }
    $("#board").append(divRow);
  }
});
#board {
  margin: 0;
  width: 256px;
  height: 256px;
  border: solid 1px #333;
}

#board .row {
  margin: 0;
}

.square {
  height: 32px;
  width: 32px;
  background: #efefef;
  float: left;
}

.square.white {
  background: #fff;
}

.square.black {
  background: #333;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="board"></div>
Sodhi saab
  • 2,238
  • 1
  • 16
  • 30
0

The following code will print chess board using only HTML and JavaScript.

<script>
    document.write("<table border='1' width='200' height='200'>");
    for(var i=1; i<=8; i++)
    {
    document.write("<tr>");
    for(var j=1; j<=8; j++)
    {
    if((i+j)%2!=0)
    {
    document.write("<td bgcolor='white'></td>");
    }
    else
    {
    document.write("<td bgcolor='black'></td>");
    }
    }
    document.write("</tr>");
    }
    document.write("</table>");
    </script>
NachuArun
  • 29
  • 5
0

You should try this one this will really work

<DOCTYPE html>
<html>

<head>
    <style>
        .chessBoard {
            display: inline-block;
            border: 2px solid lightGray;
        }

        .chessBoard div {
            line-height: 1px;
        }

        .chessBoard span {
            display: inline-block;
            width: 32px;
            height: 32px;
            background-color: snow;
        }
    </style>
</head>

<body>
    <div class="chessBoard" id="chessBoardNormal"></div>
    <div class="chessBoard" id="chessBoardRandom"></div>
    <script>
        function colorNormal(x, y, color) {
            var chessBoard = document.getElementById("chessBoardNormal");
            for (var i = 0; i < x; i++) {
                var row = chessBoard.appendChild(document.createElement("div"));
                for (var j = 0; j < y; j++) {
                    var span = document.createElement('span');
                    if (i & 1) { // odd
                        if (j & 1) { // white

                        } else { // black
                            span.style.backgroundColor = color;
                        }
                    } else { // even
                        if (j & 1) { // black
                            span.style.backgroundColor = color;
                        }
                    }

                    row.appendChild(span);
                }
            }
        }

        function colorRandom(x, y) {
            colorNormal(8, 8, Math.random() > .5 ? 'black' : '#CFD65C');
        }

        function getRandomHexColor() {
            return '#' + Math.floor(Math.random() * 16777215).toString(16);
        }

        colorNormal(8, 8, 'black');
    </script>
</body>

</html>
Kumar Ajay A.K
  • 123
  • 1
  • 8
0

My idea is simple, if row is even then start with white piece otherwise start with black piece.

HTML:

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

Javascript:

const fragment = document.createDocumentFragment();
const board = document.getElementById("mainChessBoard");
const size = 8;

for (let i = 0; i < size; i++) {
  let start = i % 2 === 0 ? 0 : 1; // if row is even then start with white otherwise start with black;
  for (let j = 0; j < size; j++) {
    const div = document.createElement('div');
    div.classList.add(start === 1 ? "black" : "white");
    fragment.appendChild(div);
    start = start === 1 ? 0 : 1;
  }
}

board.appendChild(fragment);
Jagrati
  • 8,910
  • 7
  • 30
  • 42
-1

Javascript:

var i, j, clas;
for (i = 0; i < 8; i++) {
    for (j = 0; j < 8; j++) {
        clas = '';

        if (j === 0) clas = 'first ';
        else if (j === 7) clas = 'last ';
        clas += (i % 2 == j % 2) ? 'white' : 'black';

        var field = document.createElement('div');
        field.className = clas;
        document.body.appendChild(field);
    }
}

CSS:

div {
    float: left;
    width: 20px;
    height: 20px;
}
.first {
    clear: left;
}
.black {
    background: black;
}
.white {
    background: red;
}

Sample: http://jsfiddle.net/YJnXG/2/

Igor Jerosimić
  • 12,987
  • 6
  • 43
  • 51
-4

You mean like this?

.... html.....
&lt;table&gt;
&lt;tr&gt;
&lt;script language='javascript'&gt;
&lt;!--
alternate();
//--&gt;
&lt;/script&gt;
&lt;/tr&gt;
&lt;/table&gt;
....more html.....

function alternate()
{
var numOfCells = 6;
var num = 0;
for (i = 0; i &lt; numOfCells ; i++)
{
txt = "&lt;td bgColor='";
txt += (num % 2 == 0) ? 'red' : 'black';
txt += "'&gt;"
document.write(txt);
num++;
}
}

The % sign is mod; it returns the remainder of a division. the "(...) ? ... : ...;" construction is like an if/else. If the condition is true, the first option -- else the second.

Glen Morse
  • 2,721
  • 7
  • 47
  • 92
  • Thank you! It took me good five seconds before I figure out < and > :) – Tyrant May 22 '13 at 06:00
  • 1
    Considering this is in a code block you might want to replace the lt's and gt's with actual 's - otherwise this HTML code won't do anything but visually display HTML code to anyone opening that page. – doppelgreener Sep 09 '13 at 00:52