Creating Chessboard with JavascriptCompact a switch case in javascriptCreate GUID / UUID in JavaScript?How do...

Hidden fifths between tenor and soprano in Tchaikovsky's "Guide to harmony"

Can you pop microwave popcorn on a stove?

Poor management handling of recent sickness and how to approach my return?

antimatter annihilation in stars

Owner keeps cutting corners and poaching workers for his other company

Is it right to use the ideas of non-winning designers in a design contest?

If every star in the universe except the Sun were destroyed, would we die?

How should Thaumaturgy's "three times as loud as normal" be interpreted?

Is there a "right" way to interpret a novel, if not, how do we make sure our novel is interpreted correctly?

Bit floating sequence

Complex conjugate and transpose "with respect to a basis"

Infinitely many primes

Why does PAUSE key have a long make code and no break code?

After a few interviews, What should I do after told to wait?

How to plot two curves with the same area under?

Is every sentence we write or utter either true or false?

What makes things real?

More than three domains hosted on the same IP address

How can I hint that my character isn't real?

How strong is aircraft-grade spruce?

What precisely does the commonly reported network hash rate refer to?

How invisible hand adjusts stock prices if company is listed on multiple exchanges, under multiple currencies, and one of the currencies plunges?

Contour plot of a sequence of spheres with increasing radius

Why are UK MPs allowed to abstain (but it counts as a no)?



Creating Chessboard with Javascript


Compact a switch case in javascriptCreate GUID / UUID in JavaScript?How do JavaScript closures work?What is the most efficient way to deep clone an object in JavaScript?Which “href” value should I use for JavaScript links, “#” or “javascript:void(0)”?How do I remove a property from a JavaScript object?Which equals operator (== vs ===) should be used in JavaScript comparisons?How do I include a JavaScript file in another JavaScript file?What does “use strict” do in JavaScript, and what is the reasoning behind it?How to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







6















I am creating a chessboard with Javascript. I already managed to create the board itself, but I'm having trouble giving every field its fitting class (black or white).



I managed to correctly assign the classes for the first row, but am having trouble with the rest of the board. I know there are probably easier solutions to this.



<!DOCTYPE html>
<html>
<head>
<title>Chess</title>
<link rel="stylesheet" type="text/css" href="assets/css/chess.css">
<script type="text/javascript" src="assets/js/lib/jquery.js"></script>

</head>
<body onload="initGame()">
<h1>Chess</h1>
<div id="board">

</div>

<script type="text/javascript" src="assets/js/chess.js"></script>
</body>
</html>


body{
text-align: center;
background-color: rgb(30, 30, 30);
}
#board{
margin: 0 auto;
width: 800px;
height: 800px;
background-color: white;
}
#board div{
width: 100px;
height: 100px;
float: left;
}
.white{
background-color: white;
border: 1px solid black;
}
.black{
background-color: black;
border: 1px solid white;
}


const board = [];
const boardElement = document.getElementById("board");


function initGame(){
for(var y = 0; y < 8; y++){
var row = [];
for(var x = 0; x < 8; x++){
var cell = {};
cell.element = document.createElement("div")
boardElement.appendChild(cell.element);
row.push(cell);
}
board.push(row);
}
$("#board div").addClass("field white");
for(var i = 0; i < board.length * 8; i++){
if((i % 7) == 0 && i != 0){
$(".field")[i].className = "field black";
i++;
}
else if((i % 7) == 0){
i++;
}
$(".field")[i].className = "field black";
i++;
}
startGame();
}
function startGame(){

}



The current output:










share|improve this question






















  • 1





    You could accomplish the black/white with css using nth-child.

    – ray hatfield
    10 hours ago











  • Yeah, but I thought that assigning classes would make it easier to actually move the chess pieces and determine the possible moves for each piece.

    – Roehrich1004
    10 hours ago






  • 1





    Altering the loop counter variable i conditionally makes for a very confusing algorithm. What was your idea?

    – Bergi
    10 hours ago











  • at first, I wanted to make every second field black, but then I realized that it switches every round and tried to find an easy workaround.

    – Roehrich1004
    10 hours ago






  • 2





    Your logic for moving pieces should not depend on any CSS, only on coordinates. So go with nth-child like in this answer

    – trincot
    9 hours ago


















6















I am creating a chessboard with Javascript. I already managed to create the board itself, but I'm having trouble giving every field its fitting class (black or white).



I managed to correctly assign the classes for the first row, but am having trouble with the rest of the board. I know there are probably easier solutions to this.



<!DOCTYPE html>
<html>
<head>
<title>Chess</title>
<link rel="stylesheet" type="text/css" href="assets/css/chess.css">
<script type="text/javascript" src="assets/js/lib/jquery.js"></script>

</head>
<body onload="initGame()">
<h1>Chess</h1>
<div id="board">

</div>

<script type="text/javascript" src="assets/js/chess.js"></script>
</body>
</html>


body{
text-align: center;
background-color: rgb(30, 30, 30);
}
#board{
margin: 0 auto;
width: 800px;
height: 800px;
background-color: white;
}
#board div{
width: 100px;
height: 100px;
float: left;
}
.white{
background-color: white;
border: 1px solid black;
}
.black{
background-color: black;
border: 1px solid white;
}


const board = [];
const boardElement = document.getElementById("board");


function initGame(){
for(var y = 0; y < 8; y++){
var row = [];
for(var x = 0; x < 8; x++){
var cell = {};
cell.element = document.createElement("div")
boardElement.appendChild(cell.element);
row.push(cell);
}
board.push(row);
}
$("#board div").addClass("field white");
for(var i = 0; i < board.length * 8; i++){
if((i % 7) == 0 && i != 0){
$(".field")[i].className = "field black";
i++;
}
else if((i % 7) == 0){
i++;
}
$(".field")[i].className = "field black";
i++;
}
startGame();
}
function startGame(){

}



The current output:










share|improve this question






















  • 1





    You could accomplish the black/white with css using nth-child.

    – ray hatfield
    10 hours ago











  • Yeah, but I thought that assigning classes would make it easier to actually move the chess pieces and determine the possible moves for each piece.

    – Roehrich1004
    10 hours ago






  • 1





    Altering the loop counter variable i conditionally makes for a very confusing algorithm. What was your idea?

    – Bergi
    10 hours ago











  • at first, I wanted to make every second field black, but then I realized that it switches every round and tried to find an easy workaround.

    – Roehrich1004
    10 hours ago






  • 2





    Your logic for moving pieces should not depend on any CSS, only on coordinates. So go with nth-child like in this answer

    – trincot
    9 hours ago














6












6








6


2






I am creating a chessboard with Javascript. I already managed to create the board itself, but I'm having trouble giving every field its fitting class (black or white).



I managed to correctly assign the classes for the first row, but am having trouble with the rest of the board. I know there are probably easier solutions to this.



<!DOCTYPE html>
<html>
<head>
<title>Chess</title>
<link rel="stylesheet" type="text/css" href="assets/css/chess.css">
<script type="text/javascript" src="assets/js/lib/jquery.js"></script>

</head>
<body onload="initGame()">
<h1>Chess</h1>
<div id="board">

</div>

<script type="text/javascript" src="assets/js/chess.js"></script>
</body>
</html>


body{
text-align: center;
background-color: rgb(30, 30, 30);
}
#board{
margin: 0 auto;
width: 800px;
height: 800px;
background-color: white;
}
#board div{
width: 100px;
height: 100px;
float: left;
}
.white{
background-color: white;
border: 1px solid black;
}
.black{
background-color: black;
border: 1px solid white;
}


const board = [];
const boardElement = document.getElementById("board");


function initGame(){
for(var y = 0; y < 8; y++){
var row = [];
for(var x = 0; x < 8; x++){
var cell = {};
cell.element = document.createElement("div")
boardElement.appendChild(cell.element);
row.push(cell);
}
board.push(row);
}
$("#board div").addClass("field white");
for(var i = 0; i < board.length * 8; i++){
if((i % 7) == 0 && i != 0){
$(".field")[i].className = "field black";
i++;
}
else if((i % 7) == 0){
i++;
}
$(".field")[i].className = "field black";
i++;
}
startGame();
}
function startGame(){

}



The current output:










share|improve this question
















I am creating a chessboard with Javascript. I already managed to create the board itself, but I'm having trouble giving every field its fitting class (black or white).



I managed to correctly assign the classes for the first row, but am having trouble with the rest of the board. I know there are probably easier solutions to this.



<!DOCTYPE html>
<html>
<head>
<title>Chess</title>
<link rel="stylesheet" type="text/css" href="assets/css/chess.css">
<script type="text/javascript" src="assets/js/lib/jquery.js"></script>

</head>
<body onload="initGame()">
<h1>Chess</h1>
<div id="board">

</div>

<script type="text/javascript" src="assets/js/chess.js"></script>
</body>
</html>


body{
text-align: center;
background-color: rgb(30, 30, 30);
}
#board{
margin: 0 auto;
width: 800px;
height: 800px;
background-color: white;
}
#board div{
width: 100px;
height: 100px;
float: left;
}
.white{
background-color: white;
border: 1px solid black;
}
.black{
background-color: black;
border: 1px solid white;
}


const board = [];
const boardElement = document.getElementById("board");


function initGame(){
for(var y = 0; y < 8; y++){
var row = [];
for(var x = 0; x < 8; x++){
var cell = {};
cell.element = document.createElement("div")
boardElement.appendChild(cell.element);
row.push(cell);
}
board.push(row);
}
$("#board div").addClass("field white");
for(var i = 0; i < board.length * 8; i++){
if((i % 7) == 0 && i != 0){
$(".field")[i].className = "field black";
i++;
}
else if((i % 7) == 0){
i++;
}
$(".field")[i].className = "field black";
i++;
}
startGame();
}
function startGame(){

}



The current output:







javascript html






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 10 hours ago









ggorlen

12.1k4 gold badges13 silver badges30 bronze badges




12.1k4 gold badges13 silver badges30 bronze badges










asked 10 hours ago









Roehrich1004Roehrich1004

426 bronze badges




426 bronze badges











  • 1





    You could accomplish the black/white with css using nth-child.

    – ray hatfield
    10 hours ago











  • Yeah, but I thought that assigning classes would make it easier to actually move the chess pieces and determine the possible moves for each piece.

    – Roehrich1004
    10 hours ago






  • 1





    Altering the loop counter variable i conditionally makes for a very confusing algorithm. What was your idea?

    – Bergi
    10 hours ago











  • at first, I wanted to make every second field black, but then I realized that it switches every round and tried to find an easy workaround.

    – Roehrich1004
    10 hours ago






  • 2





    Your logic for moving pieces should not depend on any CSS, only on coordinates. So go with nth-child like in this answer

    – trincot
    9 hours ago














  • 1





    You could accomplish the black/white with css using nth-child.

    – ray hatfield
    10 hours ago











  • Yeah, but I thought that assigning classes would make it easier to actually move the chess pieces and determine the possible moves for each piece.

    – Roehrich1004
    10 hours ago






  • 1





    Altering the loop counter variable i conditionally makes for a very confusing algorithm. What was your idea?

    – Bergi
    10 hours ago











  • at first, I wanted to make every second field black, but then I realized that it switches every round and tried to find an easy workaround.

    – Roehrich1004
    10 hours ago






  • 2





    Your logic for moving pieces should not depend on any CSS, only on coordinates. So go with nth-child like in this answer

    – trincot
    9 hours ago








1




1





You could accomplish the black/white with css using nth-child.

– ray hatfield
10 hours ago





You could accomplish the black/white with css using nth-child.

– ray hatfield
10 hours ago













Yeah, but I thought that assigning classes would make it easier to actually move the chess pieces and determine the possible moves for each piece.

– Roehrich1004
10 hours ago





Yeah, but I thought that assigning classes would make it easier to actually move the chess pieces and determine the possible moves for each piece.

– Roehrich1004
10 hours ago




1




1





Altering the loop counter variable i conditionally makes for a very confusing algorithm. What was your idea?

– Bergi
10 hours ago





Altering the loop counter variable i conditionally makes for a very confusing algorithm. What was your idea?

– Bergi
10 hours ago













at first, I wanted to make every second field black, but then I realized that it switches every round and tried to find an easy workaround.

– Roehrich1004
10 hours ago





at first, I wanted to make every second field black, but then I realized that it switches every round and tried to find an easy workaround.

– Roehrich1004
10 hours ago




2




2





Your logic for moving pieces should not depend on any CSS, only on coordinates. So go with nth-child like in this answer

– trincot
9 hours ago





Your logic for moving pieces should not depend on any CSS, only on coordinates. So go with nth-child like in this answer

– trincot
9 hours ago












3 Answers
3






active

oldest

votes


















5
















You can cut down your initGame logic to just add white class when y and x are either both odd or both even. You can do this by y%2 == x%2. You won't need the extra for loop.!



function initGame(){
for(var y = 0; y < 8; y++){
var row = [];
for(var x = 0; x < 8; x++){
var cell = {};
cell.element = document.createElement("div")
if(y%2 == x%2)
{
cell.element.className = "field white";
}
else
{
cell.element.className = "field black";
}
boardElement.appendChild(cell.element);
row.push(cell);
}
board.push(row);
}

startGame();
}





share|improve this answer








New contributor



Karthik is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






















  • y%2 == x%2 nice!

    – kmgt
    9 hours ago



















1
















Not sure what other functionality you'd need, but for generating the board you could do something like this:






const md = () => document.createElement('div');

function makeBoard (container, length = 8) {
for ( let i = 0; i < length; i++) {
const row = md();
Array.from({length}).forEach(() => row.appendChild(md()));
container.appendChild(row);
}
}

makeBoard(document.getElementById('board'));

#board > div {
display: flex;
min-height: 32px;
}

#board > div > div {
flex: 0 0 32px;
background: tomato;
}

#board > div:nth-child(even) > div:nth-child(even) {
background: bisque;
}

#board > div:nth-child(odd) > div:nth-child(odd) {
background: bisque;
}

<div id="board"></div>








share|improve this answer

































    1
















    A solution with swapping array:



    var colors = ['white', 'black'];

    $("#board div").each(function(i) {
    if((i % 2) == 0)
    $(this).addClass(colors[0]);
    else
    $(this).addClass(colors[1]);
    if([8,16,24,32,40,48,56,64].indexOf((i + 1)) > -1)
    colors = colors.reverse();
    });





    const board = [];
    const boardElement = document.getElementById("board");


    function initGame(){
    for(var y = 0; y < 8; y++){
    var row = [];
    for(var x = 0; x < 8; x++){
    var cell = {};
    cell.element = document.createElement("div")
    boardElement.appendChild(cell.element);
    row.push(cell);
    }
    board.push(row);
    }

    $("#board div").addClass('field');

    var colors = ['white', 'black'];

    $("#board div").each(function(i) {
    if((i % 2) == 0)
    $(this).addClass(colors[0]);
    else
    $(this).addClass(colors[1]);
    if([8,16,24,32,40,48,56,64].indexOf((i + 1)) > -1)
    colors = colors.reverse();
    });

    // startGame();
    }

    body{
    text-align: center;
    background-color: rgb(30, 30, 30);
    }
    #board{
    margin: 0 auto;
    width: 400px;
    height: 400px;
    background-color: white;
    }
    #board div{
    width: 50px;
    height: 50px;
    float: left;
    box-sizing: border-box;
    }
    .white{
    background-color: white;
    border: 1px solid black;
    }
    .black{
    background-color: black;
    border: 1px solid white;
    }

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <!DOCTYPE html>
    <html>
    <head>
    <title>Chess</title>
    <link rel="stylesheet" type="text/css" href="assets/css/chess.css">
    <script type="text/javascript" src="assets/js/lib/jquery.js"></script>

    </head>
    <body onload="initGame()">
    <h1>Chess</h1>
    <div id="board">

    </div>

    <script type="text/javascript" src="assets/js/chess.js"></script>
    </body>
    </html>








    share|improve this answer




























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });















      draft saved

      draft discarded
















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f57836901%2fcreating-chessboard-with-javascript%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      5
















      You can cut down your initGame logic to just add white class when y and x are either both odd or both even. You can do this by y%2 == x%2. You won't need the extra for loop.!



      function initGame(){
      for(var y = 0; y < 8; y++){
      var row = [];
      for(var x = 0; x < 8; x++){
      var cell = {};
      cell.element = document.createElement("div")
      if(y%2 == x%2)
      {
      cell.element.className = "field white";
      }
      else
      {
      cell.element.className = "field black";
      }
      boardElement.appendChild(cell.element);
      row.push(cell);
      }
      board.push(row);
      }

      startGame();
      }





      share|improve this answer








      New contributor



      Karthik is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















      • y%2 == x%2 nice!

        – kmgt
        9 hours ago
















      5
















      You can cut down your initGame logic to just add white class when y and x are either both odd or both even. You can do this by y%2 == x%2. You won't need the extra for loop.!



      function initGame(){
      for(var y = 0; y < 8; y++){
      var row = [];
      for(var x = 0; x < 8; x++){
      var cell = {};
      cell.element = document.createElement("div")
      if(y%2 == x%2)
      {
      cell.element.className = "field white";
      }
      else
      {
      cell.element.className = "field black";
      }
      boardElement.appendChild(cell.element);
      row.push(cell);
      }
      board.push(row);
      }

      startGame();
      }





      share|improve this answer








      New contributor



      Karthik is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















      • y%2 == x%2 nice!

        – kmgt
        9 hours ago














      5














      5










      5









      You can cut down your initGame logic to just add white class when y and x are either both odd or both even. You can do this by y%2 == x%2. You won't need the extra for loop.!



      function initGame(){
      for(var y = 0; y < 8; y++){
      var row = [];
      for(var x = 0; x < 8; x++){
      var cell = {};
      cell.element = document.createElement("div")
      if(y%2 == x%2)
      {
      cell.element.className = "field white";
      }
      else
      {
      cell.element.className = "field black";
      }
      boardElement.appendChild(cell.element);
      row.push(cell);
      }
      board.push(row);
      }

      startGame();
      }





      share|improve this answer








      New contributor



      Karthik is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      You can cut down your initGame logic to just add white class when y and x are either both odd or both even. You can do this by y%2 == x%2. You won't need the extra for loop.!



      function initGame(){
      for(var y = 0; y < 8; y++){
      var row = [];
      for(var x = 0; x < 8; x++){
      var cell = {};
      cell.element = document.createElement("div")
      if(y%2 == x%2)
      {
      cell.element.className = "field white";
      }
      else
      {
      cell.element.className = "field black";
      }
      boardElement.appendChild(cell.element);
      row.push(cell);
      }
      board.push(row);
      }

      startGame();
      }






      share|improve this answer








      New contributor



      Karthik is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.








      share|improve this answer



      share|improve this answer






      New contributor



      Karthik is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.








      answered 9 hours ago









      KarthikKarthik

      664 bronze badges




      664 bronze badges




      New contributor



      Karthik is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.




      New contributor




      Karthik is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.


















      • y%2 == x%2 nice!

        – kmgt
        9 hours ago



















      • y%2 == x%2 nice!

        – kmgt
        9 hours ago

















      y%2 == x%2 nice!

      – kmgt
      9 hours ago





      y%2 == x%2 nice!

      – kmgt
      9 hours ago













      1
















      Not sure what other functionality you'd need, but for generating the board you could do something like this:






      const md = () => document.createElement('div');

      function makeBoard (container, length = 8) {
      for ( let i = 0; i < length; i++) {
      const row = md();
      Array.from({length}).forEach(() => row.appendChild(md()));
      container.appendChild(row);
      }
      }

      makeBoard(document.getElementById('board'));

      #board > div {
      display: flex;
      min-height: 32px;
      }

      #board > div > div {
      flex: 0 0 32px;
      background: tomato;
      }

      #board > div:nth-child(even) > div:nth-child(even) {
      background: bisque;
      }

      #board > div:nth-child(odd) > div:nth-child(odd) {
      background: bisque;
      }

      <div id="board"></div>








      share|improve this answer






























        1
















        Not sure what other functionality you'd need, but for generating the board you could do something like this:






        const md = () => document.createElement('div');

        function makeBoard (container, length = 8) {
        for ( let i = 0; i < length; i++) {
        const row = md();
        Array.from({length}).forEach(() => row.appendChild(md()));
        container.appendChild(row);
        }
        }

        makeBoard(document.getElementById('board'));

        #board > div {
        display: flex;
        min-height: 32px;
        }

        #board > div > div {
        flex: 0 0 32px;
        background: tomato;
        }

        #board > div:nth-child(even) > div:nth-child(even) {
        background: bisque;
        }

        #board > div:nth-child(odd) > div:nth-child(odd) {
        background: bisque;
        }

        <div id="board"></div>








        share|improve this answer




























          1














          1










          1









          Not sure what other functionality you'd need, but for generating the board you could do something like this:






          const md = () => document.createElement('div');

          function makeBoard (container, length = 8) {
          for ( let i = 0; i < length; i++) {
          const row = md();
          Array.from({length}).forEach(() => row.appendChild(md()));
          container.appendChild(row);
          }
          }

          makeBoard(document.getElementById('board'));

          #board > div {
          display: flex;
          min-height: 32px;
          }

          #board > div > div {
          flex: 0 0 32px;
          background: tomato;
          }

          #board > div:nth-child(even) > div:nth-child(even) {
          background: bisque;
          }

          #board > div:nth-child(odd) > div:nth-child(odd) {
          background: bisque;
          }

          <div id="board"></div>








          share|improve this answer













          Not sure what other functionality you'd need, but for generating the board you could do something like this:






          const md = () => document.createElement('div');

          function makeBoard (container, length = 8) {
          for ( let i = 0; i < length; i++) {
          const row = md();
          Array.from({length}).forEach(() => row.appendChild(md()));
          container.appendChild(row);
          }
          }

          makeBoard(document.getElementById('board'));

          #board > div {
          display: flex;
          min-height: 32px;
          }

          #board > div > div {
          flex: 0 0 32px;
          background: tomato;
          }

          #board > div:nth-child(even) > div:nth-child(even) {
          background: bisque;
          }

          #board > div:nth-child(odd) > div:nth-child(odd) {
          background: bisque;
          }

          <div id="board"></div>








          const md = () => document.createElement('div');

          function makeBoard (container, length = 8) {
          for ( let i = 0; i < length; i++) {
          const row = md();
          Array.from({length}).forEach(() => row.appendChild(md()));
          container.appendChild(row);
          }
          }

          makeBoard(document.getElementById('board'));

          #board > div {
          display: flex;
          min-height: 32px;
          }

          #board > div > div {
          flex: 0 0 32px;
          background: tomato;
          }

          #board > div:nth-child(even) > div:nth-child(even) {
          background: bisque;
          }

          #board > div:nth-child(odd) > div:nth-child(odd) {
          background: bisque;
          }

          <div id="board"></div>





          const md = () => document.createElement('div');

          function makeBoard (container, length = 8) {
          for ( let i = 0; i < length; i++) {
          const row = md();
          Array.from({length}).forEach(() => row.appendChild(md()));
          container.appendChild(row);
          }
          }

          makeBoard(document.getElementById('board'));

          #board > div {
          display: flex;
          min-height: 32px;
          }

          #board > div > div {
          flex: 0 0 32px;
          background: tomato;
          }

          #board > div:nth-child(even) > div:nth-child(even) {
          background: bisque;
          }

          #board > div:nth-child(odd) > div:nth-child(odd) {
          background: bisque;
          }

          <div id="board"></div>






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 9 hours ago









          ray hatfieldray hatfield

          6,4281 gold badge15 silver badges12 bronze badges




          6,4281 gold badge15 silver badges12 bronze badges


























              1
















              A solution with swapping array:



              var colors = ['white', 'black'];

              $("#board div").each(function(i) {
              if((i % 2) == 0)
              $(this).addClass(colors[0]);
              else
              $(this).addClass(colors[1]);
              if([8,16,24,32,40,48,56,64].indexOf((i + 1)) > -1)
              colors = colors.reverse();
              });





              const board = [];
              const boardElement = document.getElementById("board");


              function initGame(){
              for(var y = 0; y < 8; y++){
              var row = [];
              for(var x = 0; x < 8; x++){
              var cell = {};
              cell.element = document.createElement("div")
              boardElement.appendChild(cell.element);
              row.push(cell);
              }
              board.push(row);
              }

              $("#board div").addClass('field');

              var colors = ['white', 'black'];

              $("#board div").each(function(i) {
              if((i % 2) == 0)
              $(this).addClass(colors[0]);
              else
              $(this).addClass(colors[1]);
              if([8,16,24,32,40,48,56,64].indexOf((i + 1)) > -1)
              colors = colors.reverse();
              });

              // startGame();
              }

              body{
              text-align: center;
              background-color: rgb(30, 30, 30);
              }
              #board{
              margin: 0 auto;
              width: 400px;
              height: 400px;
              background-color: white;
              }
              #board div{
              width: 50px;
              height: 50px;
              float: left;
              box-sizing: border-box;
              }
              .white{
              background-color: white;
              border: 1px solid black;
              }
              .black{
              background-color: black;
              border: 1px solid white;
              }

              <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
              <!DOCTYPE html>
              <html>
              <head>
              <title>Chess</title>
              <link rel="stylesheet" type="text/css" href="assets/css/chess.css">
              <script type="text/javascript" src="assets/js/lib/jquery.js"></script>

              </head>
              <body onload="initGame()">
              <h1>Chess</h1>
              <div id="board">

              </div>

              <script type="text/javascript" src="assets/js/chess.js"></script>
              </body>
              </html>








              share|improve this answer






























                1
















                A solution with swapping array:



                var colors = ['white', 'black'];

                $("#board div").each(function(i) {
                if((i % 2) == 0)
                $(this).addClass(colors[0]);
                else
                $(this).addClass(colors[1]);
                if([8,16,24,32,40,48,56,64].indexOf((i + 1)) > -1)
                colors = colors.reverse();
                });





                const board = [];
                const boardElement = document.getElementById("board");


                function initGame(){
                for(var y = 0; y < 8; y++){
                var row = [];
                for(var x = 0; x < 8; x++){
                var cell = {};
                cell.element = document.createElement("div")
                boardElement.appendChild(cell.element);
                row.push(cell);
                }
                board.push(row);
                }

                $("#board div").addClass('field');

                var colors = ['white', 'black'];

                $("#board div").each(function(i) {
                if((i % 2) == 0)
                $(this).addClass(colors[0]);
                else
                $(this).addClass(colors[1]);
                if([8,16,24,32,40,48,56,64].indexOf((i + 1)) > -1)
                colors = colors.reverse();
                });

                // startGame();
                }

                body{
                text-align: center;
                background-color: rgb(30, 30, 30);
                }
                #board{
                margin: 0 auto;
                width: 400px;
                height: 400px;
                background-color: white;
                }
                #board div{
                width: 50px;
                height: 50px;
                float: left;
                box-sizing: border-box;
                }
                .white{
                background-color: white;
                border: 1px solid black;
                }
                .black{
                background-color: black;
                border: 1px solid white;
                }

                <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
                <!DOCTYPE html>
                <html>
                <head>
                <title>Chess</title>
                <link rel="stylesheet" type="text/css" href="assets/css/chess.css">
                <script type="text/javascript" src="assets/js/lib/jquery.js"></script>

                </head>
                <body onload="initGame()">
                <h1>Chess</h1>
                <div id="board">

                </div>

                <script type="text/javascript" src="assets/js/chess.js"></script>
                </body>
                </html>








                share|improve this answer




























                  1














                  1










                  1









                  A solution with swapping array:



                  var colors = ['white', 'black'];

                  $("#board div").each(function(i) {
                  if((i % 2) == 0)
                  $(this).addClass(colors[0]);
                  else
                  $(this).addClass(colors[1]);
                  if([8,16,24,32,40,48,56,64].indexOf((i + 1)) > -1)
                  colors = colors.reverse();
                  });





                  const board = [];
                  const boardElement = document.getElementById("board");


                  function initGame(){
                  for(var y = 0; y < 8; y++){
                  var row = [];
                  for(var x = 0; x < 8; x++){
                  var cell = {};
                  cell.element = document.createElement("div")
                  boardElement.appendChild(cell.element);
                  row.push(cell);
                  }
                  board.push(row);
                  }

                  $("#board div").addClass('field');

                  var colors = ['white', 'black'];

                  $("#board div").each(function(i) {
                  if((i % 2) == 0)
                  $(this).addClass(colors[0]);
                  else
                  $(this).addClass(colors[1]);
                  if([8,16,24,32,40,48,56,64].indexOf((i + 1)) > -1)
                  colors = colors.reverse();
                  });

                  // startGame();
                  }

                  body{
                  text-align: center;
                  background-color: rgb(30, 30, 30);
                  }
                  #board{
                  margin: 0 auto;
                  width: 400px;
                  height: 400px;
                  background-color: white;
                  }
                  #board div{
                  width: 50px;
                  height: 50px;
                  float: left;
                  box-sizing: border-box;
                  }
                  .white{
                  background-color: white;
                  border: 1px solid black;
                  }
                  .black{
                  background-color: black;
                  border: 1px solid white;
                  }

                  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
                  <!DOCTYPE html>
                  <html>
                  <head>
                  <title>Chess</title>
                  <link rel="stylesheet" type="text/css" href="assets/css/chess.css">
                  <script type="text/javascript" src="assets/js/lib/jquery.js"></script>

                  </head>
                  <body onload="initGame()">
                  <h1>Chess</h1>
                  <div id="board">

                  </div>

                  <script type="text/javascript" src="assets/js/chess.js"></script>
                  </body>
                  </html>








                  share|improve this answer













                  A solution with swapping array:



                  var colors = ['white', 'black'];

                  $("#board div").each(function(i) {
                  if((i % 2) == 0)
                  $(this).addClass(colors[0]);
                  else
                  $(this).addClass(colors[1]);
                  if([8,16,24,32,40,48,56,64].indexOf((i + 1)) > -1)
                  colors = colors.reverse();
                  });





                  const board = [];
                  const boardElement = document.getElementById("board");


                  function initGame(){
                  for(var y = 0; y < 8; y++){
                  var row = [];
                  for(var x = 0; x < 8; x++){
                  var cell = {};
                  cell.element = document.createElement("div")
                  boardElement.appendChild(cell.element);
                  row.push(cell);
                  }
                  board.push(row);
                  }

                  $("#board div").addClass('field');

                  var colors = ['white', 'black'];

                  $("#board div").each(function(i) {
                  if((i % 2) == 0)
                  $(this).addClass(colors[0]);
                  else
                  $(this).addClass(colors[1]);
                  if([8,16,24,32,40,48,56,64].indexOf((i + 1)) > -1)
                  colors = colors.reverse();
                  });

                  // startGame();
                  }

                  body{
                  text-align: center;
                  background-color: rgb(30, 30, 30);
                  }
                  #board{
                  margin: 0 auto;
                  width: 400px;
                  height: 400px;
                  background-color: white;
                  }
                  #board div{
                  width: 50px;
                  height: 50px;
                  float: left;
                  box-sizing: border-box;
                  }
                  .white{
                  background-color: white;
                  border: 1px solid black;
                  }
                  .black{
                  background-color: black;
                  border: 1px solid white;
                  }

                  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
                  <!DOCTYPE html>
                  <html>
                  <head>
                  <title>Chess</title>
                  <link rel="stylesheet" type="text/css" href="assets/css/chess.css">
                  <script type="text/javascript" src="assets/js/lib/jquery.js"></script>

                  </head>
                  <body onload="initGame()">
                  <h1>Chess</h1>
                  <div id="board">

                  </div>

                  <script type="text/javascript" src="assets/js/chess.js"></script>
                  </body>
                  </html>








                  const board = [];
                  const boardElement = document.getElementById("board");


                  function initGame(){
                  for(var y = 0; y < 8; y++){
                  var row = [];
                  for(var x = 0; x < 8; x++){
                  var cell = {};
                  cell.element = document.createElement("div")
                  boardElement.appendChild(cell.element);
                  row.push(cell);
                  }
                  board.push(row);
                  }

                  $("#board div").addClass('field');

                  var colors = ['white', 'black'];

                  $("#board div").each(function(i) {
                  if((i % 2) == 0)
                  $(this).addClass(colors[0]);
                  else
                  $(this).addClass(colors[1]);
                  if([8,16,24,32,40,48,56,64].indexOf((i + 1)) > -1)
                  colors = colors.reverse();
                  });

                  // startGame();
                  }

                  body{
                  text-align: center;
                  background-color: rgb(30, 30, 30);
                  }
                  #board{
                  margin: 0 auto;
                  width: 400px;
                  height: 400px;
                  background-color: white;
                  }
                  #board div{
                  width: 50px;
                  height: 50px;
                  float: left;
                  box-sizing: border-box;
                  }
                  .white{
                  background-color: white;
                  border: 1px solid black;
                  }
                  .black{
                  background-color: black;
                  border: 1px solid white;
                  }

                  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
                  <!DOCTYPE html>
                  <html>
                  <head>
                  <title>Chess</title>
                  <link rel="stylesheet" type="text/css" href="assets/css/chess.css">
                  <script type="text/javascript" src="assets/js/lib/jquery.js"></script>

                  </head>
                  <body onload="initGame()">
                  <h1>Chess</h1>
                  <div id="board">

                  </div>

                  <script type="text/javascript" src="assets/js/chess.js"></script>
                  </body>
                  </html>





                  const board = [];
                  const boardElement = document.getElementById("board");


                  function initGame(){
                  for(var y = 0; y < 8; y++){
                  var row = [];
                  for(var x = 0; x < 8; x++){
                  var cell = {};
                  cell.element = document.createElement("div")
                  boardElement.appendChild(cell.element);
                  row.push(cell);
                  }
                  board.push(row);
                  }

                  $("#board div").addClass('field');

                  var colors = ['white', 'black'];

                  $("#board div").each(function(i) {
                  if((i % 2) == 0)
                  $(this).addClass(colors[0]);
                  else
                  $(this).addClass(colors[1]);
                  if([8,16,24,32,40,48,56,64].indexOf((i + 1)) > -1)
                  colors = colors.reverse();
                  });

                  // startGame();
                  }

                  body{
                  text-align: center;
                  background-color: rgb(30, 30, 30);
                  }
                  #board{
                  margin: 0 auto;
                  width: 400px;
                  height: 400px;
                  background-color: white;
                  }
                  #board div{
                  width: 50px;
                  height: 50px;
                  float: left;
                  box-sizing: border-box;
                  }
                  .white{
                  background-color: white;
                  border: 1px solid black;
                  }
                  .black{
                  background-color: black;
                  border: 1px solid white;
                  }

                  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
                  <!DOCTYPE html>
                  <html>
                  <head>
                  <title>Chess</title>
                  <link rel="stylesheet" type="text/css" href="assets/css/chess.css">
                  <script type="text/javascript" src="assets/js/lib/jquery.js"></script>

                  </head>
                  <body onload="initGame()">
                  <h1>Chess</h1>
                  <div id="board">

                  </div>

                  <script type="text/javascript" src="assets/js/chess.js"></script>
                  </body>
                  </html>






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 9 hours ago









                  kmgtkmgt

                  1,0251 silver badge16 bronze badges




                  1,0251 silver badge16 bronze badges


































                      draft saved

                      draft discarded



















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f57836901%2fcreating-chessboard-with-javascript%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Taj Mahal Inhaltsverzeichnis Aufbau | Geschichte | 350-Jahr-Feier | Heutige Bedeutung | Siehe auch |...

                      Baia Sprie Cuprins Etimologie | Istorie | Demografie | Politică și administrație | Arii naturale...

                      Ciclooctatetraenă Vezi și | Bibliografie | Meniu de navigare637866text4148569-500570979m