I'm building a Tic Tac toe game... but I can't figure it out how to use the function addEventListener and if that is the only problem in there. I've seen some tutorial, and mostly of them use onclick on the markup but I would like tu use addEventListener, so I can call it once for every box that I have. I really need some help please.
HTML
<div id="message"> </div>
<div class="console">
<div id="firstRow">
<div id="box1" class="myBox"></div>
<div id="box2" class="myBox"></div>
<div id="box3" class="myBox"></div>
</div>
<div class="secondRow">
<div id="box4" class="myBox"></div>
<div id="box5" class="myBox"></div>
<div id="box6" class="myBox"></div>
</div>
<div class="thirdRow">
<div id="box7" class="myBox"></div>
<div id="box8" class="myBox"></div>
<div id="box9" class="myBox"></div>
</div>
</div>
Javascript
window.addEventListener('DOMContentLoaded', function() {
var startGame = function() {
for (var i =1; i <= 9; i++) {
clearBox();
}
var turn = 'X';
var winner = null;
setMessage(turn + 'gets to start.');
}
function setMessage(msg) {
document.getElementById('message').innerHTML = msg;
}
function nextMove(box) {
if(winner !== null){
setMessage(winner +' already won the game');
}
if(box.innerHTML === ''){
box.innerHTML = turn;
switchTurn();
}
else {
setMessage('Choose another box.');
}
}
function switchTurn() {
if(checkWinner(turn)) {
setMessage('Congratulations, ' + turn + 'wins!');
winner = turn;
}
else if(turn === 'X') {
turn = "O";
setMessage('Its ' + turn + 'turn.');
}
else {
turn = 'X';
setMessage('Its ' + turn + 'turn.');
}
}
function checkWinner(move) {
var result = false;
if( checkRow(1, 2, 3, move) ||
checkRow(4, 5, 6, move) ||
checkRow(7, 8, 9, move) ||
checkRow(1, 4, 7, move) ||
checkRow(2, 5, 8, move) ||
checkRow(3, 6, 9, move) ||
checkRow(1, 5, 9, move) ||
checkRow(3, 5, 7, move)) {
result = true;
}
return result;
}
function checkRow(a, b, c, move) {
var result = false;
if(getBox(a) === move && getBox(b) === move && getBox(c) === move) {
result = true;
}
return result;
}
//to get the number of my box so I can checkROw() and clearBox()
function getBox(number) {
return document.getElementById('box' + number).innerHTML;
}
function clearBox(number) {
return document.getElementById('box' + number).innerHTML = '';
};
});
});