JavaScript Project #1 – Two Player Tic Tac Toe

Welcome in a tutorial which guide, how to write Tic Tac Toe game in JavaScript. First of all, before you start, you should know basics of JavaScript and jQuery. On my blog, I already have series for newbies in this language.

So, I assume that you know basics of JavaScript. Open your favourite code editor and write default structure of HTML. On the end of file attach jQuery library and JavaScript file which will be filled with our code.

At this step, we should stop for a while. Let us think about the typical gameplay of Tic Tac Toe. The game is for two players, which alternately choose one from nine fields. A player who first capture three fields in a vertical, horizontal or diagonal row, win.

Thus, we need a board with nine fields (in our case, we use input type=”buttons” or just buttons).  Also, by clicking on them, the player should mark his choose. To make this we use onclick event trigger. But wait, how we know about a number of fields? We need to add an ID attribute to each button.

We are going to write this in JS and run when document load. So, our script file should look something like

as output to above, we have 3×3 board with the reset button.

Now we need to write checkField function, which checks if clicked button is the empty field. If the field is empty, the button should be marked and turn toggled.

The second to last is to check rows to find correctly positioned marks.

Finally, we are going to write gameOver function, which informs us, which player win and function to reset board when the player clicks the reset button.

So, our complete code is

You can play demo at





Leave a Reply

Your email address will not be published. Required fields are marked *