Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change global variable from event function

I am trying to learn Javascript.

I watched some Javascript course on Youtube and am trying to create my first project.

Project should be simple tic-tac-toe game.

Functionality: First click on box should fill with "X" Second click on another box should fill with "Y" Third click on another box should fill with "X" again and so on until all boxes will be filled with character.

there is my codes HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
<div class="main">
<table>
    <tr>
        <td class="b1-1"></td>
        <td class="b1-2"></td>
        <td class="b1-3"></td>
    </tr>
    <tr>
        <td class="b2-1"></td>
        <td class="b2-2"></td>
        <td class="b2-3"></td>
    </tr>
    <tr>
        <td class="b3-1"></td>
        <td class="b3-2"></td>
        <td class="b3-3"></td>
    </tr>
</table>
</div>
<script src="script.js" type="text/javascript"></script>
</body>
</html>

CSS

.main {
    padding: 100px 0;
    width: 360px;
    margin: 0 auto;
}

table, tbody {
    margin: 0;
    padding: 0;
    width: 360px;
    height: 360px;
}

tr {
    width:360px;
    height: 120px;
    margin: 0;
    padding: 0;
}

td {
    text-align: center;
    width:120px;
    height: 120px;
    border: 1px solid #333;
    margin: 0;
    padding: 0;
    font-size: 50px;
}

Javascript

var action = document.querySelectorAll('td');
var gameState = 0;
for (var i = 0; i <= action.length - 1; i++) {
    getClassName = "." + action[i].classList.value;
        if (gameState === 0) {
            document.querySelector(getClassName).addEventListener("click", chasviX(i));
        } else {
            document.querySelector(getClassName).addEventListener("click", chasviO(i));
        }
}

function chasviX(cord) {
        document.querySelector("." + action[cord].classList.value).addEventListener("click", event => {
            document.querySelector("." + action[cord].classList.value).textContent = "X";
            gameState = 1;
        });
};

function chasviO(cord) {
        document.querySelector("." + action[cord].classList.value).addEventListener("click", event => {
            document.querySelector("." + action[cord].classList.value).textContent = "O";
            gameState = 0;
        });
};

There is project link also - https://jsfiddle.net/qwy2k571/

At the moment each box is filling with "X". I know i didn't understand closures and scope chains exactly but please give me an correct code to understand it by example.

Thanks in advance and best regards.

like image 918
Levan Sakvarelidze Avatar asked Aug 02 '26 19:08

Levan Sakvarelidze


2 Answers

Since you are using querySelectorAll which will give a collection, you can iterate that and directly add event listener to it. Aslo you are adding multiple eventlistener which is not required

var action = document.querySelectorAll('td');
var gameState = 0;
action.forEach((item) => {
  item.addEventListener('click', (e) => {
    if (gameState === 0) {
      e.target.textContent = "X";
      gameState = 1;
    } else {
      e.target.textContent = "0";
      gameState = 0;
    }
  })

})
.main {
  padding: 100px 0;
  width: 360px;
  margin: 0 auto;
}

table,
tbody {
  margin: 0;
  padding: 0;
  width: 360px;
  height: 360px;
}

tr {
  width: 360px;
  height: 120px;
  margin: 0;
  padding: 0;
}

td {
  text-align: center;
  width: 120px;
  height: 120px;
  border: 1px solid #333;
  margin: 0;
  padding: 0;
  font-size: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main">
  <table>
    <tr>
      <td class="b1-1"></td>
      <td class="b1-2"></td>
      <td class="b1-3"></td>
    </tr>
    <tr>
      <td class="b2-1"></td>
      <td class="b2-2"></td>
      <td class="b2-3"></td>
    </tr>
    <tr>
      <td class="b3-1"></td>
      <td class="b3-2"></td>
      <td class="b3-3"></td>
    </tr>
  </table>
</div>
like image 165
brk Avatar answered Aug 04 '26 09:08

brk


Here I made a working jsfiddle: https://jsfiddle.net/1jnkepLg/1/

I simplified the JS part to:

var gameState = 0; // Holds the current game state
var cells = document.getElementsByTagName("td"); // list of cells of the game board

// attach an event listener at each cell. 
for (var i=0;i<cells.length;i++) 
{    
    cells[i].addEventListener("click", chasvi);
}   

function chasvi() 
{
       // in event callbacks "this" refers to the element that triggered the event. In this case, it is the TD element.
       this.textContent = gameState ? "X" : "0";

       // switch the game state
       gameState = !gameState;

}

In this case, one event listener is enough, you can determine what X|0 to draw at the callback function.

like image 36
Eriks Klotins Avatar answered Aug 04 '26 08:08

Eriks Klotins



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!