javascripteventsjsobject

Javascript Object for Tic Tac Toe game


Complete newbie here on the Javascript topic. I am trying to code out a Tic Tac Toe game, while using JS' Objects to save code space. I figured I might create a JS Object which will all 9 fields defined in the HTML code with ids 'one' to 'nine' as values, and then also have a custom method which can be used to swap value's textContent as follows:

var fields = {
    one: document.querySelector('#one'),
    two: document.querySelector('#two'),
    three: document.querySelector('#three'),
    four: document.querySelector('#four'),
    five: document.querySelector('#five'),
    six: document.querySelector('#six'),
    seven: document.querySelector('#seven'),
    eight: document.querySelector('#eight'),
    nine: document.querySelector('#nine'),
    swap: function(element) {
        if (this.element.textContent === "") {
            this.element.textContent = "X";
        } else if (this.element.textContent === "X") {
            this.element.textContent = "O";
        } else {
            this.element.textContent = "";
        }
    }
}

Then, I figured I would just add a bunch of addEventListeners like so:

fields['one'].addEventListener('click', fields.swap(fields['one']));

The thing is, I am probably totally treating this concept as it would operate in Python, and I am probably messing up the syntax here. Can anyone give me some ideas on where I am making an error?

The code copied above does not work at the moment.

HTML that it works with is as follows (I have omitted formatting here to save on space):

<body>
  <div class="container">
    <table id="gameboard">
      <tr class="row">
      <td id="one" class="gameField">X</td>
      <td id="two" class="gameField">X</td>
      <td id="three" class="gameField">X</td>
    </tr>
    <tr class="row">
      <td id="four" class="gameField">X</td>
      <td id="five" class="gameField">X</td>
      <td id="six" class="gameField">X</td>
    </tr>
    <tr class="row">
      <td id="seven" class="gameField">X</td>
      <td id="eight" class="gameField">X</td>
      <td id="nine" class="gameField">X</td>
    </tr>
  </table>
</div>


Solution

  • Separate you swap function out of your object and just get rid of the object all together. Add a class to all of the HTMLElements you wish to add an EventListener to and then query them all using the following:

    <div id="one" class="your-class"></div>
    <div id="two" class="your-class"></div>
    
    function swap(element) {
       if (element.textContent === ""){
          element.textContent = "X";
        }else if (element.textContent === "X") {
          element.textContent = "O";
        }else {
          element.textContent = "";
        }
    }
    
    document.querySelectorAll('.your-class').forEach(function (element) {
       element.addEventListener('click', swap(element));
    });