Chess table

Please, what is wrong int his code?
It does not write lines properlz in w3school online…
Many thanks!!!

<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>

Hi,

You’d need to clear the floats at the end of the 8th square and although you are adding a break to do this the break is not the same height as the div and therefore the next float just snags on the break and doesn’t go to the start of the line.

It looks as though your routine would only produce coloured columns and not a chess board appearance as you need to change the colouring order on each row.

Bear in mind I’m a CSSer not a JSerr so this is probably too verbose but seems to work.


<DOCTYPE html>
<html>
<head>
<style>
div {
	border:1px solid black;
	width:20px;
	height:20px;
	float:left;
	background:#fff;
	color:#000;
	margin:0 -1px -1px 0;
}
.clear { clear:both }
.black {background:#000;color:#fff;}
.white {background:#fff;color:#000;}

</style>
</head>
<body>
<script type="text/javascript">
// create a chess table 8x8.
(function () {
    var count = 0;
    var toggle = true;
    var square = "";
    var square1 = "white";
    var square2 = "black";

    while (count < 8) {
        for (var i = 0; i < 8; i++) {
            square = (i % 2 === 0 ? square1 : square2);
            if (i === 0) {
                document.write('<div class=\\"clear ' + square + '\\"></div>');
            } else {
                document.write('<div class=\\"' + square + '\\"></div>');
            }
        }
        toggle = !toggle;
        if (!toggle) {
            square1 = "black";
            square2 = "white"
        } else {
            square1 = "white";
            square2 = "black"
        }

        count++;
    }
})();
</script>
</body>
</html>

I believe using document.write is not ideal other than for learning so I will leave it to one of the fine JS experts here to amend accordingly.

document.write does have its legitimate uses, but at the same time it’s really easy to misuse it.
This page explains why

A better way here would to use a safe DOM manipulation method:

var row = 0;
while (row < 8) {
	var column = 0;
	while (column < 8) {
		var square = document.createElement("div");
		if(row%2 === 0){
			square.className = (column%2 === 0)? "white" : "black";
		} else {
			square.className = (column%2 === 0)? "black" : "white";
		}

		if (column === 0){
			square.className += " clear";
		}
		document.body.appendChild(square);
		column++
	}
	row++;
}

Yes, that’s much neater :slight_smile:

It shouldn’t even be taught any more except in Advanced JavaScript classes. The situations where it is actually needed are rather advanced. Beginners and intermediate users of JavaScript never need it and just get confused if they learn it.

Using innerHTML is the way beginners should currently start out.

<div id="something"></div>
<script>
document.getElementById('something').innerHTML =  'content to insert that used to go in a document.write back before Netscape 4 died';
</script>

Of course once you get to something a little more involved than just posting text into the page with JavaScript, using DOM calls are often the better alternative but a JavaScript beginner doesn’t generally learn those until about lesson four or five.

A little more compact :slight_smile:

var classNames = ["white", "black"];
for(var i=0; i<64; i++){
  var square = document.createElement("div");
  if (i && i%8 === 0){ 
  	classNames.reverse();
  	square.className = "clear "
  }
  square.className += (i%2 === 0)? classNames[0] : classNames[1];
  document.body.appendChild(square);
}

Thanks for the clarification Stephen :slight_smile:

That’s neat and I can almost see how it works :slight_smile: You reverse the array on every new row (apart from the first) so that the classes are swapped around to create the alternate colouring.

This doesn’t use canvas, so I probably would :

  • either create a HTML template row (no colors) and clone it seven times by JS
  • or create the whole thing in HTML (again, no colors on the squares)
    and I would definitely use CSS to add color classes to the squares.

Right @Paul_O_B ? :wink:


.row:nth-of-type(2n+1) > .square:nth-of-type(2n+1) {}
.row:nth-of-type(2n+1) > .square:nth-of-type(2n) {}
.row:nth-of-type(2n) > .square:nth-of-type(2n+1) {}
.row:nth-of-type(2n) > .square:nth-of-type(2n) {}

or


.row:nth-child(odd) > .square:nth-child(odd) {}
.row:nth-child(odd) > .square:nth-child(even) {}
.row:nth-child(even) > .square:nth-child(odd) {}
.row:nth-child(even) > .square:nth-child(even) {}

After all, @Pullo ‘white’ or ‘black’ class names are not very semantic, are they? :wink:

Otherwise, I would just use canvas. That’s when JS use for the whole thing would be justifiable.


<html>
 <head>
  <script type="application/javascript">
    function draw() {
      var canvas = document.getElementById("canvas");
      if (canvas.getContext) {
        var ctx = canvas.getContext("2d");

        ctx.fillStyle = "rgb(0,0,0)";
        ctx.fillRect (0, 0, 50, 50);

        ctx.fillStyle = "rgb(225, 225, 225)";
        ctx.fillRect (50, 0, 50, 50);
      }
    }
  </script>
 </head>
 <body onload="draw();">
   <canvas id="canvas" width="150" height="150"></canvas>
 </body>
</html>

Something like this: http://geeksretreat.wordpress.com/2012/06/01/html-5-canvas-chess-board/

CSS !! Now you’re talking my language :slight_smile:


<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style type="text/css">
body:after {
	content:" ";
	display:block;
	background-color:#f00;
	background-image: linear-gradient(45deg, black 25%, transparent 25%, transparent 75%, black 75%), linear-gradient(45deg, black 25%, transparent 25%, transparent 75%, black 75%);
	background-size:100px 100px;
	background-position: 0 0, 50px 50px;
	width:400px;
	height:400px;
	border:5px solid #fc0;
}
</style>
</head>

<body>
</body>
</html>

Or with a full set of chequers as well :slight_smile:


<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style type="text/css">
html { background:#000 }
body {
	background-color:#f00;
	background-image: linear-gradient(45deg, black 25%, transparent 25%, transparent 75%, black 75%), linear-gradient(45deg, black 25%, transparent 25%, transparent 75%, black 75%);
	background-size:100px 100px;
	background-position: 0 0, 50px 50px;
	width:400px;
	height:400px;
	border:5px solid #fc0;
}
body:before {
	background-color: transparent;
	background-image: radial-gradient(blue 35%, transparent 16%), radial-gradient(blue 35%, transparent 16%);
	background-position: -16px -15px, 30px 35px;
	background-size: 102px 102px;
	content: " ";
	height: 163px;
	left: 0;
	position: absolute;
	top: 250px;
	width: 412px;
	z-index: 2;
	clip: rect(10px, 412px, 163px, 10px);
}
body:after {
	background-color: transparent;
	background-image: radial-gradient(white 35%, transparent 16%), radial-gradient(white 35%, transparent 16%);
	background-position: -16px -15px, 30px 35px;
	background-size: 102px 102px;
	clip: rect(10px, 462px, 163px, 60px);
	content: " ";
	height: 163px;
	left: -48px;
	position: absolute;
	top: 0;
	width: 462px;
	z-index: 2;
}
</style>
</head>

<body>
</body>
</html>

Aplogies to the OP for going off topic a little :slight_smile:

I think that was my fault originally:blush: (I was just trying to keep it simple for the OP to follow - that’s my excuse anyway :)).

Show off! :slight_smile:

OK, here is what I had in mind when I said I’d create a HTML template row (no colors) and clone it seven times by JS and I would definitely use CSS to add color classes to the squares: http://jsbin.com/oKUXeli/2/

Nice demo :slight_smile: I will have to study it and as you say it would make sense to use CSS to style the board.

You could lose the first part of the css and just set all cells to black by default and then you only need to worry about the white ones ;).


#chessboard .row .square {
  width: 20px;
  height: 20px;
  float: left;
[B]  background-color: black;[/B]
}
 #chessboard .row.row:nth-of-type(2n+1) .square:nth-of-type(2n),
#chessboard .row.row:nth-of-type(2n) .square:nth-of-type(2n+1){
  background-color: white;
}


Off Topic:

I’ve played a wee bit of Chess and in terms of the game, referring to the sides as “white” and “black” is the norm. It’s the board’s squares that are not always white and black but always “lighter” and “darker” regardless of the hue. So semantically speaking for square colors, “white” and “black” wouldn’t be as correct as “lighter” and “darker”. But I digress

Thanks. :slight_smile:

Yes, I know. I prefer it this way though. :slight_smile: For me, on a larger code base, it would be easier to maintain. Usually, CSS is also structured based on different style sections: layout, colors etcetera.

@Mittineague Good point. Indeed, the chess pieces (and the players) are referred to as white and black, the squares are said to be light and dark.

I’ve modified my example a bit, the JS part: http://jsbin.com/oKUXeli/4/

[ot] I followed the thread and was curious to see how the chess board could be created using PHP…

http://www.johns-jokes.com/downloads/sp-b/chess-board/index.php

@Paul your solution was really neat.

[/ot]

This proves to be useful when using canvas: draw the whole canvas in a light color, and then only draw the dark squares. Here it is: http://jsbin.com/oKUXeli/7/