New to Rust? Grab our free Rust for Beginners eBook Get it free →
Tic Tac Toe JavaScript: Build a Browser Game

Building a tic-tac-toe game for a browser means creating a nine-cell board where X and O take turns. JavaScript stores the moves and checks for a completed winning line or a full board.
In this piece, I’ll show how to connect the board to JavaScript and test the rules that end or restart a round.
TL;DR
A tic-tac-toe game needs a nine-cell board, a turn variable, eight winning lines, and checks for occupied cells, wins, draws and restart.
- Build the board with nine semantic buttons in HTML and a three-column CSS grid.
- Keep the JavaScript array as the game state and update button text after each accepted click.
- Check for a win before checking for a full board, then stop input until restart.
What is a tic-tac-toe game?
Tic-tac-toe is played on a three-by-three board. X and O take turns, and a line across the board ends the round.
Each cell represents one square, and its position supplies the index used by the game logic.
Build a tic-tac-toe game step by step
Put index.html, style.css and tictactoe.js in one directory, then link the stylesheet and script from the page.
Step 1: Add the board and status in HTML
Use button elements for cells so they work with a keyboard or pointer. Give each one the data-cell attribute and a location label. The status announces whose turn it is or whether play ended.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Tic-tac-toe</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Tic-tac-toe</h1>
<p id="status" aria-live="polite">X's turn</p>
<div class="board">
<button data-cell aria-label="Top left"></button>
<button data-cell aria-label="Top middle"></button>
<button data-cell aria-label="Top right"></button>
<button data-cell aria-label="Middle left"></button>
<button data-cell aria-label="Center"></button>
<button data-cell aria-label="Middle right"></button>
<button data-cell aria-label="Bottom left"></button>
<button data-cell aria-label="Bottom middle"></button>
<button data-cell aria-label="Bottom right"></button>
</div>
<button id="restart" type="button">Restart</button>
<script src="tictactoe.js"></script>
</body>
</html>
The repeated attribute lets JavaScript select the board cells without generated IDs.
Step 2: Arrange the cells with CSS
A grid layout keeps the cells in three equal columns. Set a large touch target and a visible focus outline for the active button.
body { font: 1rem sans-serif; text-align: center; margin: 2rem; }
.board { display: grid; grid-template-columns: repeat(3, 5rem); gap: .35rem; justify-content: center; }
.board button { width: 5rem; height: 5rem; font-size: 2rem; }
button:focus-visible { outline: 3px solid #146c94; outline-offset: 2px; }
#status { min-height: 1.5em; }
On a narrow screen, reduce the page margin or use responsive cell sizing so all three columns fit.
The nine cells form three rows, with spacing between neighboring squares. Tab moves focus through the buttons. Their labels identify each square, and the outline marks focus.
Step 3: Store turns and winning lines
Start with an array of nine empty strings and set the first player to X.
const cells = [...document.querySelectorAll("[data-cell]")];
const status = document.querySelector("#status");
const restart = document.querySelector("#restart");
let board = Array(9).fill("");
let current = "X";
let finished = false;
const wins = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]];
The spread syntax turns the selector result into an array, and the line list keeps each winning condition in one place.
An empty string represents an unplayed square, while X or O represents a move.
Each winning route is stored as three array positions, with the rows, columns and diagonals listed in order.
querySelectorAll returns matches in document order, so the button order must stay aligned with the indexes. A larger board needs a rule generator because winning lines depend on its dimensions.
For this fixed board, the eight listed lines map directly to its rows, columns and diagonals.
Step 4: Accept a click and decide the result
Reject an ended game or occupied position. Then check the winning lines before testing for a draw.
function finishTurn(index) {
if (finished || board[index]) return;
board[index] = current;
cells[index].textContent = current;
const won = wins.some(line => line.every(i => board[i] === current));
if (won) {
status.textContent = `${current} wins`;
finished = true;
} else if (board.every(Boolean)) {
status.textContent = "Draw";
finished = true;
} else {
current = current === "X" ? "O" : "X";
status.textContent = `${current}'s turn`;
}
}
cells.forEach((cell, index) => cell.addEventListener("click", () => finishTurn(index)));
The some method succeeds when one line is complete, and every confirms all three positions match the active player.
The handler returns for a finished game or filled square before assignment. Once a move is accepted, its mark appears in the button before the result is evaluated.
The winning check uses current before the turn changes. If the player completes a line, the status names that player and the finished flag prevents a later click from adding another mark. Otherwise the full-board check decides whether the move filled the last square without completing a line.
With empty strings for unused cells, board.every(Boolean) is true only when each square contains X or O. If you choose another empty value, replace this test with a comparison that matches it.
Step 5: Restart the round
Reset the array and the displayed cells together so a new round starts with matching state and controls.
restart.addEventListener("click", () => {
board = Array(9).fill("");
current = "X";
finished = false;
cells.forEach(cell => { cell.textContent = ""; });
status.textContent = "X's turn";
});
Save the handlers and state above in tictactoe.js. Open index.html in a browser and play a complete round. MDN explains this event model in its addEventListener reference.
The script tag sits after the board markup, so the buttons exist before JavaScript queries them. If you move the script into the head, defer its execution or wait for the document before selecting elements.
Try a short round by placing X in the top-left square and O in the middle-left square, then complete a row with X. The text below the title should change after each legal move. Selecting a previously filled square should leave both its mark and the next player’s turn intact.
Direct listeners are a reasonable fit for nine fixed buttons because each button receives one callback at initialization. If the page later creates and removes cells dynamically, a listener on the board container can handle events that bubble from new buttons, but it also needs to check that the event target is a cell.
This setup needs no build step or third-party package. It expects a browser that supports const, let, arrow functions and template strings.
If the browser reports a missing script, check that tictactoe.js is beside index.html and that the src spelling and letter case match. A syntax error also prevents later handlers from registering, so correct the first console error before testing again.
If the board appears but clicks do nothing, verify that the status, restart button and nine cells exist before listeners register. A misspelled status id makes querySelector return null, so compare the HTML id with the JavaScript selector.
The status line leaves the finished board visible instead of resetting it immediately after a result.
A computer opponent needs a move-selection rule, while online play needs shared state between browsers.
Handle game edge cases
Small rule checks prevent the board from accepting invalid moves or showing the wrong end state. I ran the game logic with a simulated click sequence using node game_test.js.
The run printed this output:
Win sequence: X(0), O(3), X(1), O(4), X(2)
Status after win: X wins
Status after extra click: X wins
Status after restart: X’s turn
Empty cells after restart: 9
Occupied cell after second click: X
Draw sequence status: Draw

The run confirms a win, a draw, an ignored duplicate move and a working restart. The harness exercises the same JavaScript source with lightweight button and click objects.
| Case | What can go wrong | Rule to apply |
|---|---|---|
| Occupied cell clicked again | The mark or turn changes twice | Return when board[index] already has a mark |
| Move after a win | The next player alters a finished round | Set finished and reject later clicks |
| Final move makes a line | The game is incorrectly called a draw | Check winning lines before board.every(Boolean) |
| Restart clears only the display | Old internal marks affect the next round | Reset array, player, finished flag and button text |
Check the selector against the HTML before investigating turn logic.
Keep status updates concise so assistive technology can announce the result without repeating the board.
A single click handler can process every cell because the loop passes each button’s index. It does not. The loop attaches the same callback to each cell and passes its index, so one function applies the same legality and win rules regardless of which button receives the click.
The callback closes over board, current and finished, so it can update state without returning a value to the button. It also changes the cell and status text after an accepted action.
A round can accept no more than nine moves because each legal move fills one empty position. A win can occur while empty cells remain, which is why the terminal state also blocks later clicks.
This example lets two people take turns. An opponent that chooses moves needs a strategy beyond the rule engine shown here.
Conclusion
Keep the state transitions explicit: accept a legal move, decide the result, then prepare the next turn or restart.
Next, try adding a score counter that survives a round reset, or compare the structure with CodeForGeek’s Snake game built with HTML5 Canvas and JavaScript. A grid-based alternative is the Sudoku puzzle game built with JavaScript. Keep turn changes and terminal checks separate as features grow.
FAQ
These answers cover common questions about creating the basic browser game.
How do you create a tic-tac-toe game in JavaScript?
Create nine clickable cells, store their values in an array, alternate X and O, and check eight winning lines after each accepted move.
How does the game know when the board is a draw?
After checking for a win, test whether every board position is filled. If so, the round is a draw.
How do you stop a player from changing an occupied cell?
Return from the click handler when the chosen array position already contains X or O.




