Create a chess board with Vanilla JS
Tags: javascript, webdev, beginners, tutorial
Published: 2022-10-31 05:47:40

In this tutorial I'll run you through the steps for creating a chess board. Creating a chess board covers very fundamental skills for a JavaScript developer, including conditionals, loops, and iterator methods. Enjoy!

# Step 1 (Assuming you have your files set up)

Create your HTML boilerplate. Here's mine:

```
<!DOCTYPE html>

<html lang="en">
    <head>
        <title>Chess</title>
        <link rel="stylesheet" href="styles/styles.css" />
        <meta charset="UTF-8" />
        <script src="scripts/index.js" defer></script>
    </head>
    <body>
        <div class="chessBoard"></div>
    </body>
</html>
```

This is a very basic boilerplate for our HTML file. Notice we have linked our CSS and JS files with the `<link>` and `<script>` tags. It's important to note that I've included a defer attribute. If this is not included your scripts will not execute.

# Step 2

Style the ".chessBoard":

```
div.chessBoard {
    width: 800px;
    height: 800px;
    border: 5px solid #000;
    margin: auto; // centers board
    line-height: 0px; // no line space on inline-blocks 
}
```
Here we've styled the border for the chess board which will inhabit all of the tiles for the board. The board itself is 800x800 pixels, and each tile will be 100x100 pixels. `margin: auto;` will center the board. Since the squares themselves will be inline-blocks to get them to wrap, they will behave as text does and automatically create vertical space above and below them. To prevent this, we add `line-height: 0px;` to the parent element of the squares.

# Step 3

Render the squares:

```
function renderSquares(){
    let numOfSquares = 0;
    const chessBoard = document.querySelector(".chessBoard")
    const chessSquareArray = []
    while (numOfSquares < 64){
        chessSquare = document.createElement("div")
        chessSquare.classList.add("chessSquare")
        chessSquareArray.push(chessSquare)
        numOfSquares += 1;
    }
    chessSquareArray.forEach((element, i) => {
        determineSquareColor(element, i)
        // determines square color in separate function
    })
    return chessSquareArray.forEach((element) => {
        return chessBoard.append(element)
    })
}

renderSquares()
```

Here we have written a function that handles creating the squares and appending it to the board. We declare a variable called `numOfSquares`, and initialize it to 0. Then we grab the chess board, and create an empty array that will begin to house the squares momentarily. We write a while loop that conditionally runs based off the value of `numOfSquares`. Since we want 64 squares, that's what we base our loop off of. Each loop we are creating a div element, assigning it a class name of `"chessSquare"`, and pushing it to the array (don't forget the increment!). Now that we have an array of all 64 squares, we iterate through it and color each one based on its position in the array. Take a look at the function below. After this, for each element in our now-styled array of squares, append it to the chess board.

# Step 4

Add logic for coloring the squares:

```
function determineSquareColor(element, i){
    if ((i >= 0 && i <= 7) || (i >= 16 && i <= 23) || (i >= 32 && i <= 39) || (i >= 48 && i <= 55)){
        return i % 2 === 0 ? element.style.backgroundColor = "#FFF" : element.style.backgroundColor = "#000";
    }
    if ((i >= 8 && i <= 15) || (i >= 24 && i <= 31) || (i >= 40 && i <= 47) || (i >= 56 && i <= 63)){
        return i % 2 !== 0 ? element.style.backgroundColor = "#FFF" : element.style.backgroundColor = "#000";
    }
}
```

The logic that handles coloring the tiles. The first row contains 8 tiles, beginning with a white tile and ending with a black tile, and vice versa each row. It's not enough to just evaluate the position of each tile based on its odd or even placement in the array. This is because each row begins and ends with a different color. We need to write two if statements. The first one determines the colors of each square for the rows that begin with a white tile. The second one determines the colors for the rows that begin with a black tile.

Remember, the reason we have access to the elements we're coloring is because we passed them in as arguments from `renderSquares()`.

# Step 5

Add dimensions to squares:

```
div.chessSquare {
    width: 100px;
    height: 100px;
    display: inline-block;
}
```

Adding these properties and values will make your squares flush with the edges, and wrap them perfectly so all 64 squares fit to the board.

# Conclusion

And there you have it! This is a great way to exercise the basics of JavaScript such as conditionals, loops, and iterator methods.