I'm having trouble displaying the X's and O's in my tic tac toe JavaScript game. Any suggestions on how to resolve this issue?

After following a couple of online tutorials for the tic tac toe project, I encountered an error in both attempts. The X's and O's were not displaying even though all other features were working fine. Below are my codes for HTML, CSS, and JavaScript. Please excuse any mistakes as I am still learning.

const playerTurn = document.querySelector('.turn');

let gameActive = true;
let currentPlayer = "X";
let gameArray = ["", "", "", "", "", "", "", "", ""];

const winMessage = () => `Player ${currentPlayer} wins!`;
const drawMessage = () => `It's a Draw!`;
const currentPlayerTurn = () => `Player ${currentPlayer}'s Turn`;

playerTurn.innerHTML = currentPlayerTurn();

function handleCellPlayed() {
  gameArray[clickedCellIndex] = currentPlayer;
  clickedCell.innerHTML = currentPlayer;
}

function handlePlayerChange() {
  currentPlayer = currentPlayer === "X" ? "O" : "X";
  gameArray.innerHTML = currentPlayerTurn();
}
const winningConditions = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8],
  [0, 3, 6],
  [1, 4, 7],
  [2, 5, 8],
  [0, 4, 8],
  [2, 4, 6]
];

function handleResultValidation() {
  let roundWon = false;
  for (let i = 0; i <= 7; i++) {
    const winCondition = winningConditions[i];
    let a = gameArray[winCondition[0]];
    let b = gameArray[winCondition[1]];
    let c = gameArray[winCondition[2]];
    if (a === '' || b === '' || c === '') {
      continue;
    }
    if (a === b && b === c) {
      roundWon = true;
      break
    }
  }
  if (roundWon) {
    playerTurn.innerHTML = winMessage();
    gameActive = false;
    return;
  }
  let roundDraw = !gameArray.includes("");
  if (roundDraw) {
    playerTurn.innerHTML = drawMessage();
    gameActive = false;
    return;
  }
  handlePlayerChange();
}

function handleCellClick() {
  const clickedCell = clickedCellEvent.target;
  const clickedCellIndex = parseInt(
    clickedCell.getAttribute('data-cell-index')
  );
  if (gameArray[clickedCellIndex] !== "" || !gameActive) {
    return;
  }
  handleCellPlayed(clickedCell, clickedCellIndex);
  handleResultValidation();
}

function handleRestartGame() {
  gameActive = true;
  currentPlayer = "X";
  gameArray = ["", "", "", "", "", "", "", "", ""];
  playerTurn.innerHTML = currentPlayerTurn();
  document.querySelectorAll('.cell')
    .forEach(cell => cell.innerHTML = "");
}

document.querySelectorAll('.cell').forEach(cell => cell.addEventListener('click', handleCellClick));
document.querySelector('.restart').addEventListener('click', handleRestartGame);
body {
  font-family: "Courier", sans-serif;
  text-align: center;
}

.game {
  display: grid;
  grid-template-columns: repeat(3, auto);
  width: 304px;
  margin: 50px auto;
}

.cell {
  font-family: "Permanent Marker", cursive;
  width: 100px;
  height: 100px;
  box-shadow: 0 0 0 1px #333333;
  border: 1px solid #333333;
  cursor: pointer;
  line-height: 100px;
  font-size: 60px;
}
<h1 class="title">Tic Tac Toe</h1>
<div class="game">
  <div data-cell-index="0" class="cell"></div>
  <div data-cell-index="1" class="cell"></div>
  <div data-cell-index="2" class="cell"></div>
  <div data-cell-index="3" class="cell"></div>
  <div data-cell-index="4" class="cell"></div>
  <div data-cell-index="5" class="cell"></div>
  <div data-cell-index="6" class="cell"></div>
  <div data-cell-index="7" class="cell"></div>
  <div data-cell-index="8" class="cell"></div>
</div>
<h2 class="turn"></h2>
<button class="restart">Restart</button>

With some modifications to my JavaScript code, I was able to make the restart button appear after a few tweaks.

Answer №1

The existing function handleCellPlayed is missing parameters, therefore it is unable to receive the clickedCell or clickedCellIndex that are being passed to it.

You can update it as follows:

function handleCellPlayed(clickedCell, clickedCellIndex) {

Answer №2

Just a quick note: handleCellPlayed() needs parameters to receive the data from data-yourvalue, which can be accessed using dataset.yourvalue.

Below is a functional example:

 // JavaScript code here...
 /* CSS styles here... */ 
 <!-- HTML markup here... --> 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing JavaScript to Retrieve Selected Parameter in SSRS Report

Currently, I am incorporating an SSRS report into my website using Iframe. I aim to share a link to the specific filtered report, which is why I require knowledge of the report's parameters. My query pertains to how I can identify these parameters (e ...

The intended functionality of clicking on an image is exclusively reserved for its immediate parent element

I have a feature on my website that displays an image gallery. When a user clicks on an image, it opens up the image in full screen similar to Facebook's theatre mode. I have written code so that when the user clicks anywhere in the container of the i ...

Curved base of the main banner image

Struggling to achieve the perfect curve at the bottom of my hero image. Any suggestions on how to accomplish this would be greatly appreciated. I am aiming for something like this: https://i.stack.imgur.com/Emxfc.png body { margin: 0; background: lig ...

Getting the value of an element using a string in JQuery

How can I achieve the following using JQuery? var test = "'#ISP'"; alert($(test).val()); I am receiving a "Syntax error, unrecognized expression." I believe I might be overlooking something here. Thank you in advance! ...

Combining 2 blocks to form a unified element

I receive a lot of HTML output like this: <div> <h4>This</h4><p>Value 9.6 m.</p> <h4>That</h4><p>Value 9.6 m.</p> <h4>The other</h4><p>Another 7.69 m.</p> <h4>And yet< ...

State is causing a conflict by allowing multiple menus to open when mapping over Menu objects

I am currently encountering an issue with my Material UI <Menu>. The problem arises when I attempt to display some data and interface functionality by mapping over a <Card>, along with adding an <IconButton> on each card that opens a menu ...

Issue with Bootstrap 5 dropdown menu extending beyond the viewport on the right side

The user dropdown in my code is cut off, even though I'm using Bootstrap 5. I came across an older article on stackoverflow suggesting to add .dropdown-menu-left or .dropdown-menu-right to the </ul>, but that didn't solve the issue for me. ...

Can you explain the contrast between EJS's render() function and renderFile() method?

const express = require('express'); const ejs = require('ejs'); const app = express(); app.engine('ejs', ejs.renderFile); app.get('/', (req, res) => { res.render('index.ejs', { ...

Troubleshooting issue: Django and Javascript - Why is my dependent dropdown feature not

I am new to using a combination of Javascript and Django. Below is the script I have written: <script> $(document).ready(function() { $("#source").change(function() { var el = $(this); var reg = ...

When running JavaScript from a .js.erb file, it gets executed while still being visible as plain text

I'm facing an issue with a form inside a popup window. Here's how it looks: <%= form_tag "/controller/action", :method => :get, :remote => true do %> ... <% end %> Within my controller: respond_to do |format| format.js end ...

Need help with styling for disabled autocomplete? Check out the attached image

I'm currently working with material-ui and react to create a basic form. Everything is functioning properly except for a small UI issue that I can't seem to figure out how to resolve. When I utilize the browser's auto-complete feature, the i ...

Importing an external JSON file into a ChartJs chart

As a newcomer to using libraries for drawing charts in JavaScript, I recently started playing around with Chartjs. However, I'm having trouble figuring out how to use getJson or any other method to load my json object and update the labels and data. I ...

Enhance the form values using HTML and Javascript before submitting them via POST

Greetings to all! Apologies if my question seems elementary, as I am relatively new to using Javascript/HTML... I am encountering an issue with PayPal integration. In the past, I have successfully implemented it with a single fixed price, but now I have ...

Guide for animating individual mapped elements in react-native?

After mapping an object array to create tag elements with details, I added an animation for the tags to zoom in on render. However, I wanted to take it further and animate each tag individually, sequentially one after the other. This appears to be a common ...

Having issues with Next.js server-side rendering when integrating API functionality

"Not building properly" means that the project is not fully completing the build process. I've developed a simple blog project with dynamic SSR that pulls data from the Notion-API to generate static blog pages. Everything functions correctly ...

jQuery can be used to obtain the label for a checkbox with a particular value

Currently, I am facing an issue with retrieving the label for a checkbox using jQuery. Let me provide you with the relevant HTML code: <div class="checkbox"> <label><input type="checkbox" name="cb_type[]" value="sold" >Sold</label ...

The React axios request triggers the UseEffect cleanup function to terminate all subscriptions and asynchronous tasks

I'm currently retrieving data from my API using axios, but the requests are not inside a useEffect function. In fact, I haven't used useEffect at all. Here's a snippet of my code: JSX: <form onSubmit={onSubmitLogin}> <div c ...

The form-group nested within a form-horizontal is exceeding the boundaries of the preceding form-group

I am currently utilizing Bootstrap 3.3.6 and have a basic form enclosed in a panel: https://i.stack.imgur.com/UOFI6.png Although it is quite simple, the alignment of the "Post" button is not displaying properly. Here is the HTML code for the form: < ...

I am having trouble getting ngFor to properly render my accessible data. Whenever I attempt to use it, it ends up breaking my code. Can someone please

When using *ngFor to iterate through data, everything appears to be working fine until attempting to access nested data within an object inside another object. For example: { "tvshow": [ { "id": "value", "time": { "clock": "valu ...

Utilizing and incorporating distinct html elements on a separate webpage

I am in the process of developing a dynamic newspaper-style website where articles will be regularly updated and replaced on the Home Page. Each article featured on the Home Page will serve as a link to a separate page for full details. These article links ...