The display function in Javascript has a tendency to work sporadically

I’ve been tasked with creating my own tic tac toe game through coding. While I am relatively new to programming, I have a strong passion for it. At the moment, I've set up a basic function to hide only the "O", leaving only the "X" visible on the grid. It's a work in progress, but I believe starting off this way is a good approach.

However, I've encountered an issue where clicking on a square causes the "O" to randomly disappear. Sometimes it happens after the first click, other times after four clicks. Can anyone shed some light on what might be causing this random behavior?

Below is the function that I'm currently using and how one of the squares is structured in HTML:

function hideO() {
  document.getElementById("O" + event.target.id).style.display = "none";
}
<div class="square" >
  <button class="1" id="1" onclick="hideO()">
      <p class="X1" id="X1">X</p>
      <p class="O1" id="O1">O</p>
  </button>
</div>

You can view all of my code here.

Answer №1

The issue lies in the fact that event.target returns the specific element you clicked on, meaning if you believe you clicked on .square, you actually clicked on the nested p element within it. One potential solution is to utilize event.currentTarget. This will always return the element where the click event was attached:

function hideO() {
  document.getElementById("O" + event.currentTarget.id).style.display = "none";
}

Additionally, I am uncertain about why you are invoking hideO from .grid. It might be best to eliminate this.

Edit: The issue may arise because event.currentTarget is only valid at the time of the event firing. Consider an alternate approach.

Adjust your hideO() function as shown below:

function hideO(btn) {
  btn.querySelector("#O" + btn.id).style.display = "none";
}

Instead of using onclick="hideO()", use onclick="hideO(this)" to pass the clicked button as a parameter. Once you have access to that button in your function, you can target the "O" element within it.

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

Determining the Missing Focus: Discovering the Vacant '":focus'" in Jquery

I am currently working on jQuery and facing an issue with input fields that have assigned ID's and attached .blur() events. I am struggling to identify the specific item that has gained focus: $("#"+field).blur(function() { console.log ($(this).attr ...

Removing extra spaces from a hyperlink using CSS

Can CSS be used to remove extra whitespaces? Within the code snippet provided, there is an additional whitespace in the <a> tag. This link is generated by a WordPress plugin and I prefer not to make changes directly to the source files of the plugin. ...

Using JavaScript's setInterval function in conjunction with Math.random to obtain a random value

Just generated some random numbers. Wondering how to dynamically update the values of these numbers every 5 seconds with fluctuations less than +/- 5% compared to the current value. Need help using the setInterval function. Here is my code for Random Pric ...

What could be causing my CORS fetch request to not send cookies to the server?

Trying to work out a CORS request using the fetch method: fetch('https://foobar.com/auth', { method: 'GET', mode: 'cors', credentials: 'include', }) The server-side code in express for impl ...

Tips for implementing server-side rendering in Jade using an Array of JSON objects instead of just a single JSON object

In my Node.js server, I am working with an array of JavaScript objects retrieved from a MySQL query. To pass this array to my Jade template, I use the following code in my router.js: data = JSON.stringify(rows[0]); res.render('yourUploads', {fro ...

Using JQuery Ajax in Internet Explorer will only execute a single time

I've encountered an issue with my code where I have set cache to false, but in Internet Explorer it only runs once. Can someone please assist me with this problem? <script type="text/javascript" src="javascripts/jq1.7.js"></script> <sc ...

Implementing Conditional Display of Span Tags in React Based on Timer Duration

In my current React project, I am facing an issue with displaying a span tag based on a boolean value. I need assistance in figuring out how to pass a value that can switch between true and false to show or hide the span tag. I tried two different methods ...

Concentrate on elements that are activated without the need for clicking

Is it possible to trigger an action when an input is focused without the focus event being initiated by a click? $('#input').focus(function(){ if(not triggered by click) { alert('Hello!'); } }); ...

"An error occurred when processing the JSON data, despite the JSON

Incorporating Ajax syntax for datatables and angularjs has been my current endeavor. Encountering an invalid JSON response with the following: self.dtOptions = DTOptionsBuilder.fromSource([{ "id": 860, "firstName": "Superman", "lastName": "Yoda" }]) How ...

typescript in conjunction with nested destructuring

ES6 has definitely made coding more efficient by reducing the number of lines, but relying solely on typescript for everything may not be the best approach. If I were to implement type checking for arguments that have been destructed multiple levels deep, ...

The status of the 'slider' may be 'undefined'

I'm really struggling to figure out how to resolve this issue, even though I suspect it's a simple fix that's eluding me... Here is the part of my code in TypeScript that's causing the error: const slideLeft = () => { cons ...

The Magic of jQuery Cross Site Fetch

It seems like this should be simple, but I am having trouble figuring it out... I'm using jQuery to fetch a remote page from a different server, grab the HTML content, and then insert that content into a hidden DIV. However, when I try to do this wit ...

Error with the setInterval() method, function is not executing

UPDATED CODE SNIPPET: <script> $.ajaxSetup({ cache : false }); function fetchMessage() { $.get("php/getMessage.php?q=1" + "&" + Date.now(), function(data) { $("#typed").typed({ ...

Steps to automatically navigate to a specific Div upon page initialization

Can someone help me understand why my code is scrolling to a div and then returning back to the top of the page? $("#Qtags").click(function(){ $('html, body').animate({'scrollTop' : $($(this).attr('href')).offset().top}, ...

Guide on how to navigate users to a new page using react-router-dom v6 within a class-based component

I am facing an issue where I need to redirect the user to '/dashboard' after logging in, but I do not want to use history.push() from react-router-dom v5.2.0 as I have react-router-dom v6 installed. Is there another alternative to achieve this re ...

Steps for setting up a barcode scanner on a smartphone (both iPhone and Android) using zxing in an html app

After reviewing different answers to my questions, I decided to try out some solutions below. The app and camera function properly on Android devices, but not on iPhones. What steps should I take? <!DOCTYPE html> <HTML> <HEAD> <script ...

HighCharts velocity gauge inquiry

I recently integrated a highcharts speedometer with PHP and MYSQL on my website. Everything seemed to be working smoothly until I added the JavaScript code for the speedometer, causing it not to display. There are no error messages, just a blank screen whe ...

How can Vue JS 3 components exchange data between each other?

I am attempting to share data from a variable favorite_count in the Favorites component located in the file Favorites.vue. My goal is to pass this data to the App Component in the App.vue file but I have been unsuccessful so far. I want any changes made to ...

A lateral sliding motion

Here is the HTML code I am working with: <div class="menuTabs"> <div class="mtabArrowLeft">Left</div> <input class="menutabBTN" name="" type="button" value="a" /> <input class="menutabBTN" name="" type="b ...

Utilize a display value while maintaining the v-model binding in Vue.js

Can't seem to figure this one out. I'm using Quasar Framework, but it seems like more of a Vue issue. I have a multiple-select UI component with a list of objects as options that I want to display. The v-model will bind to the currently selected ...