Notifying the Player of Victory in a Javascript Tic Tac Toe Game: The Winning Alert

Recently, I decided to dive into Javascript and kick off my very first game project - a Tic Tac Toe game.

If you're curious to see the code for my project, you can check it out here: Tic Tac Toe Project

One feature I'm eager to implement is a notification that pops up when a user wins the game.

To test this functionality, I tried creating a condition where the player would win if they placed 3 X's in a row on the first line:

HTML :

I added an empty paragraph with an ID that will be used specifically for displaying the notification

<p id="Notif" style="text-align : center"></p>

JS :

var Boxes = document.querySelectorAll("td")
Notif = document.getElementById("Notif")

if (Boxes[0].textContent === "X" && Boxes[1].textContent === "X" && Boxes[2].textContent === "X") {
  console.log("Check Ok");
  Notif.textContent = "You won!"
} 

However, I encountered issues and suspect it might have to do with the execution order in the script or potentially require a loop?

When I load the page, place 3 "X"s in the first line, and then run the following code snippet in the console:

if (Boxes[0].textContent === "X" && Boxes[1].textContent === "X" && Boxes[2].textContent === "X") {
  console.log("Check Ok");

I do see the log message "Check Ok".

Answer №1

It's important to note that the code is only executed once. To ensure it runs on every click on the gameboard, you'll need to enclose it within a function and call that function each time.

function checkWin(){
  if (Boxes[0].textContent === "X" && Boxes[1].textContent === "X" && Boxes[2].textContent === "X") {
     console.log("Check Ok");
     Notification.textContent = "You won!"
  } 
}
function MarkBox() {
  if (this.textContent === "") {   // === means equal for true / false questions
    this.textContent = "X"  // = means change value of variable
  } else if (this.textContent === "X") {
    this.textContent = "O"
  }
  else { this.textContent = ""}
  checkWin();
}

For a working example, you can visit repl.it

Answer №2

It appears that you are only executing your check function once. In order to make sure this is not the case, trigger the check every time the user enters an X so that it is verified with each change.

To accomplish this, you can utilize the appropriate event (such as click if Xs are set by clicking on elements, or keydown if users are inputting Xs).

Answer №3

The reason why the condition is only being called once is because it's executed when the script is initially loaded. This means that when you select X or O, the check isn't being run again. You'll need to create a function to encapsulate the condition and have it triggered every time the user makes an input. I've made some changes to your code and here is the updated version:https://repl.it/@syntax_hacker0/TickTackToe-Game

PS: Make sure to cover all possible winning scenarios in the condition.

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

A step-by-step guide on incorporating the C3 Gauge Chart into an Angular 5 application

I have been attempting to incorporate the C3 Gauge Chart from this link into a new Angular 5 application. Below is my code within chart.component.ts : import { Component, OnInit, AfterViewInit } from '@angular/core'; import * as c3 from &apos ...

Why does JQuery ajax always fail to succeed? Where could the error be?

I am attempting to create an ajax call to a php server that utilizes Wordpress. I have set up a rewrite rule to handle the redirection of ajax calls: function Ajax_rules_setup(){ add_rewrite_rule( 'ajax/([^/]*)', ...

Enlarge the size of checkboxes on Phonegap for Android

I'm currently working on a quiz application using Phonegap, incorporating HTML, JavaScript, and CSS without any additional frameworks. My problem lies in the fact that the checkboxes appear too small on Android devices. I attempted to adjust the width ...

Error: Trying to break down a non-iterable object is not valid

Currently working on an Ionic React app and encountering the following error: Error: TypeError - Invalid attempt to destructure non-iterable instance Once I run the program, the error occurs at this point: . Shown below is a snippet of my code: import ...

how to execute a javascript function in an ionic controller from the template

My journey in creating my first Ionic app has been smooth so far. I am not well-versed in UI design, so I may not be implementing the best practices, but I am making progress nonetheless... Within a template, I have encountered the following code snippet ...

What is the best way to place a list within a <div> element?

There is a <div> with an image in the background. I now want to include a list within that div, but I'm having trouble positioning it. Check out this image for reference In the image above, you can see the background and the list, but I'm ...

Uploading files using HTML 5, Ajax, and jQuery

I am attempting to utilize jQuery to upload a file by using the ajax POST method and sending the uploaded file to url:"/files/uploads" with the parameter file. To achieve this, I have set up the following input elements: <form id="fileUploadForm"> ...

What is the best way to implement data loading on scroll in HTML with AngularJS?

I'm working with a HTML Dynamic Table <div class="clearfix reportWrapper" > <div class="reportTable"> <table class="table table-bordered footerBGColor"> <thead fix-head class="headerTable"> ...

What is the process for connecting this to React ES6 getter and setter methods?

When utilizing this within an ES6 function, it is necessary to explicitly declare it in the constructor. export class MyComponent extends React.Component { constructor(){ super(); this.myFunc = this.myFunc.bind(this); } ...

Executing actions on events in a Basic jQuery sliderLearn how to handle events and execute

I utilized the slider from the bjqs plugin at after reviewing the documentation, I noticed it only offers options and lacks events/functions. I am referring to events/functions like onSlideChange and onSlideDisplay. While other plugins such as bxslid ...

The button on my VUE 3 quiz app is not changing to 'Finish' when I reach the final question

Struggling with my Vue 3 quiz app - everything works perfectly until I reach the last question. The button text should change to 'Finish' once the final question is loaded. Despite hours of searching and even using copilot, I still can't fin ...

Achieving sequential actions in Javascript without the need for state updates

One aspect of jQuery that I find impressive is its ability to chain methods like .animate() and .css(). This is made possible by utilizing the special variable "this" in the backend code. I am interested in implementing a similar method chaining mechanism ...

The paragraph tag remained visible despite the use of the hidden display property

Can you help me figure out why my code isn't working with .d-none .d-sm-block? <div class="container"> <div class="row row-content align-items-center"> <div class="col-12 col-sm-12"> <h2>heading 1&l ...

Parsing values from deeply nested objects and arrays

I've come across this issue before, but I'm having difficulty navigating through a nested structure. I can't seem to find any guidance in the right direction. Here is the object I'm attempting to parse: const nestedArray = { id ...

What is the best way to eliminate a trailing backslash from a string?

Currently, I am iterating through a list of Discord server names in node.js. The goal is to create a php file that contains an array structured like this: <?php $guildLookup = array( "164930842483761" => "guildName1", "56334 ...

Creating interactive tabs within the HTML document with AngularJS

Trying to customize the tab layout on my HTML page and I have a code similar to this: <form name="requestForm"> <div class="form-group col-md-6 md-padding"> <div class="text-primary"> <h3>Create Request</h3> ...

Having trouble getting Video.js SWF to work on Internet Explorer?

I've been working with video.js and am having trouble getting it to function properly on Internet Explorer. I have added the swf file like this: videojs.options.flash.swf = "http://vjs.zencdn.net/4.2/video-js.swf " Here is the code for the video pla ...

React and Redux: The Search for Missing Props

I am embarking on a new project using a different technology stack for the first time. In my previous job, I inherited an existing project with everything already set up. However, I am facing issues as my props are coming up as undefined and I am unsure wh ...

Is there a way for me to choose the nearest input value when clicking on a href

Is there a way to efficiently select the nearest input value when clicking on a link? I attempted to do so like this, but it returns undefined: $(".change").click(function(e){ e.preventDefault(); var qty = $(this).closest('input').val(); ...

Initiating a file download using HTML

When I try to initiate a download by specifying the filename, instead of downloading, it opens in a new tab. The code snippet below shows what I am currently using. Additionally, I am working on Chrome Browser. <!DOCTYPE html> <html> < ...