settingsAccountsettings
Menusettings

Q: Chess Board - print a chessboard of size n X n in JavaScript

+3 votes

Print a chessboard of size n X n. Create javascript function. See the example below for more information.
The input comes as a single number argument n.

Example:

Input: 3

Output:

<div class="chessboard">
  <div>
    <span class="black"></span>
    <span class="white"></span>
    <span class="black"></span>
  </div>
  <div>
    <span class="white"></span>
    <span class="black"></span>
    <span class="white"></span>
  </div>
  <div>
    <span class="black"></span>
    <span class="white"></span>
    <span class="black"></span>
  </div>
</div>

It must look like this:

print chessboard by given n number as a javascript function

asked in JavaScript category by user hues

1 Answer

+2 votes

Here is the javascript function:

function chessBoard(size) {
    let html = `<div class="chessboard">\n`;
    for (let row = 0; row < size; row++) {
        html += `  <div>\n`;
        let color = (row % 2 == 0) ? "black" : "white";
        for (let col = 0; col < size; col++) {
            html += `    <span class="${color}"></span>\n`;
            color = (color == "white") ? "black" : "white";
        }
        html += `  </div>\n`;
    }
    return html + `</div>`;
}

//chessBoard(4);//to test in the console

The HTML file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="yourjsfile.js"></script>
    <link rel="stylesheet" href="yourcssfile.css">
</head>
<body>
<script>
    let html = chessBoard(3);
    document.body.innerHTML = html;
</script>
</body>
</html>

and the CSS file:

body{
    background: #ddd;
}

.chessboard {
    display: inline-block;
}

div {
}

span {
    display: inline-block;
    width: 70px;
    height: 70px;
}

.black {
    background: black;
}

.white {
    background: white;
}

 

answered by user nikole
...