I have a grid called "gridbox" and the item "box1" should not be allowed to get clicked a 2nd time. Its for my Tik Tak Toe game.
In the function check(), it should prevent the box from getting clicked a 2nd time.
<section class="gridbox">
<div class="box1" onclick="check()"></div>
</section>
2
Answers
Welcome to Stack Overflow!
Without the rest of your code I don’t know exactly how you’re storing the state of each cell on the Tic Tac Toe board so I used an array to represent it.
We’ll create a variable called
boardState
to represent the X,O state of each cell on the board:Your
check
function will look something like this:This function takes 2 arguments,
target
: The element that was clickedi
: The index of the cell that was clickedNow, when calling the
check
function on youronclick
event, you can pass the target and index of each, with each div on the board having an increasing index. I’ve created 3 divs here that show what I’m talking about:Now when you click on the div it’ll fill in the value only if it’s already empty – otherwise, nothing will happen.
Here’s the full code to get a basic working example for 3 boxes:
It’s less about whether the box can be clicked but more that nothing should happen if a box is clicked more than once. If you use classes you can check to see if a button has an "active" class (for example), and if it doesn’t add an "active" class to it. If the code does have an active class nothing happens.
In this example I’m just adding a background colour to a boxes when it’s clicked. But you can use this to implement your TTT logic.
Additional documentation
classList
matches
Event delegation