Is there a way to stop myself from accidentally clicking twice on the same tile?

I'm currently working on a game and facing an issue where my "X" gets deleted when clicking twice on the same tile. I am able to move my "X" around, but the double-click deletion is causing trouble. I attempted using booleans but struggle with them. Is there a method to prevent this using booleans or any other approach? I am a beginner learning in school.

var firstClick = false;
var clickedTile = null;
var secondClick = false;

function movePiece(x) {
  if (secondClick == true) {
    x.innerHTML = clickedTile.innerHTML;
    clickedTile.innerHTML = "";
    secondClick = false;
    clickedTile.style.border = "1px solid black";
    clickedTile.style.height = "80px";
    clickedTile.style.width = "80px";
  } else {
    x.style.border = "3px solid red";
    x.style.width = "76px";
    x.style.height = "76px";
    clickedTile = x;
    secondClick = true;
  }
}
td {
  height: 80px;
  width: 80px;
  text-align: center;
  font-size: 300%;
}

table {
  margin-left: auto;
  margin-right: auto;
}

#title {
  text-align: center;
  font-size: 300%;
}
<div id="title">Table Game</div>
<table border=1>
  <tr>
    <td onclick="movePiece(this)">X</td>
    <td onclick="movePiece(this)"></td>
  </tr>
</table>

Answer №1

Instead of using a boolean, a class can be added or removed to show/hide the X icon.

In the solution provided below, on a click event, the script first checks if any X icons are currently active. If so, it removes the active class. Then, it adds the active class to the X icon within the clicked cell.

function movePiece(x) {
  let active = document.querySelector(".icon.active");
  if (active) {
    active.classList.remove("active")
  }
  x.querySelector(".icon").classList.add("active");
}
td {
  height: 80px;
  width: 80px;
  text-align: center;
  font-size: 300%;
}

table {
  margin-left: auto;
  margin-right: auto;
}

#title {
  text-align: center;
  font-size: 300%;
}

.icon {
  display: none;
}

.active.icon {
  border: 1px solid #000;
  height: 80px;
  width: 80px;
  display: block;
}
<div id="title">Table Game</div>
<table border=1>
  <tr>
    <td onclick="movePiece(this)">
      <div class="icon active">X</div>
    </td>
    <td onclick="movePiece(this)">
      <div class="icon">X</div>
    </td>
  </tr>
</table>

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

In what rare scenarios does JS in string concatenation within insertAdjacentHTML fail to evaluate?

On a public website that I do not own, there is a piece of JavaScript code that writes a magic pixel image to the page to call an API I provided. Here's the snippet of code: n.insertAdjacentHTML('beforebegin', '<img src=& ...

How can I make the expired date display in red color in a JavaScript date property?

In my HTML, I have 4 different dates. The expired date "END MAR 20" should be displayed in red color instead of green. The next date, "END APR 29," should be in green color. All preceding dates should also be displayed in red. I have successfully filtered ...

Prevent Chrome extension from triggering HTTP authentication popup (digest)

Currently in the process of developing a chrome extension that requires access to http-auth protected resources (webdav), particularly those using digest authentication. I have successfully implemented authentication directly within the ajax request by ut ...

nth-child selector causing tbody element to break

I have a code snippet that should alternate row colors between yellow and red. It works perfectly without using the <tbody> tags. However, when I include the <tbody> tags in my code, the layout breaks. It seems to restart with yellow at every n ...

Is it possible to implement the same technique across various child controllers in AngularJS?

I am trying to execute a function in a specific child controller. The function has the same name across all child controllers. My question is how can I call this function from a particular controller? Parent Controller: app.controller("parentctrl",functi ...

What is the best way to combine two arrays and generate a new array that includes only unique values, similar to a Union

Here are two arrays that I have: X = [ { "id": "123a", "month": 5, "markCount": 75 }, { "id": "123b", "month": 6, "markCount": 85 ...

You need to click the form submit image twice in order to make it work

Struggling to get a standard opt-in form to work with an image submit button. The script works fine with a regular submit button, but the image button requires two clicks initially and then one click after unless the page is refreshed. I believe there mig ...

AngularJs setPristine() not resetting the invalid status of a form

Is there anyone who can assist with the provided Plunker code? All you need to do is submit the form with just one required field filled out. This action will result in validation errors being displayed. When you reset the form by calling both setPristine ...

Extract the "_id" value from the array in the v-for loop and then store and reuse it in the data object // using vue-cli

Currently, I am iterating through [postArray] to retrieve various posts, each of which has its own unique "_id". My goal is to utilize this "_id" to add likes to the corresponding post. This is the v-for loop I am using: <div class="posts" v- ...

My goal is to retrieve the top three highest rated products

// @route GET /api/products/top // @desc Retrieve top-rated products // @access Available to the public router.get( '/best', asyncHandler(async (req, res) => { const bestProducts = await Product.find({}).sort({ rating: -1 }).limi ...

Are you searching for a stylish tabbed navigation menu design?

I am searching for a tabbed navigation menu specifically designed to showcase images as the tab items. Here is an example of what I have in mind: <div class="menu"> <a href="#"> <img src="images/Chrysanth ...

Customize the styling of an individual 'LI' item within an array by utilizing Jquery

Just starting out with Javascript and jQuery. Created a basic image slider that's running into a jQuery problem. Here's the HTML for the image list: <div id = "slider-auto"> <ul class= "slides"> <li class = "slide"&g ...

Generate a dynamic add to cart section for every last configurable choice, assisting with this task

Currently, I am involved in a project that involves displaying configurable options on a product page, along with querying the database to check which vendors carry the product. The list of vendors is then displayed using JavaScript. In order to make the ...

What is the best way to load the contents of an HTML file into a <div> element without it behaving as an object?

Currently, I am importing an HTML file into a <div> in this manner: function load_content() { document.getElementById('content').innerHTML = '<object type="text/html" width="100%" height="100%" data="./content.html"></obj ...

I'm encountering an issue in Atom where it says "Module 'editorconfig' cannot be found."

I keep encountering an issue in the Atom text editor where it says "Cannot find module 'editorconfig'" every time I try to save a .html file. Even though I had previously installed the EditorConfig package without any problems. How can I resolve ...

Encountering a "self is not defined" error while utilizing the Jodti-React text editor within a Next.js project

Issue with 'self is not defined' error while using jodti-react in a Next.js project import React, { useState, useRef, useMemo } from "react"; import Dashborad from "./Dashborad"; import JoditEditor from "jodit-react" ...

Discovering the process of extracting a date from the Date Picker component and displaying it in a table using Material-UI in ReactJS

I am using the Date Picker component from Material-UI for React JS to display selected dates in a table. However, I am encountering an error when trying to show the date object in a table row. Can anyone provide guidance on how to achieve this? import ...

The use of `preventDefault()` in React for the `onCopy` event is ineffective

I'm currently exploring ways to prevent the clipboard events from copying text when the onCopy event is triggered. I've tried using the onCopy handler and e.preventDefault() method, but the text is still being copied without any issues. What am I ...

I'm encountering an issue with VS Code where it is unable to identify ejs tags within my project

I'm running into an issue with Vs code where it's not recognizing ejs output tags when they're inside an html tag, like in the input tag below : <input type="checkbox" name="checkbox" value="<%=item._id%>" onChange="this.form. ...

Chrome isn't showing the Background Image

I am currently working on coding a basic HTML/CSS page and I want to include a background-image within a div element that links to a URL. Interestingly, my code is functioning properly in Safari (Mac) and Firefox but unfortunately not showing the desired r ...