McDiabeetus McDiabeetus - 2 months ago 9
CSS Question

Disable .toggleClass after an element has been clicked

I am trying to create a tictactoe game. Player 1 selects his marker, x or o, then the tictactoe board appears. Player 1's marker, let's say x, will appear at 0.5 opacity whenever he hovers over an empty cell. On click, the cell receives a .addClass("clicked"), which inserts the marker into the cell at 1 opacity. I have a .toggleClass function to switch between player markers. I would like player 1's x to remain on the board, while player 2's hovers show an o on any empty cell. The issue I am having is that after I click on a cell to add my x in, the entire board toggles class. I want every cell that does not have the class "clicked" to toggle. How can I do this?

Here is the code if player 1 chooses x

case "x":
$(function(){
$(".board").addClass("o");
$("td").click(function(){
$(this).children("p").addClass("clicked x");
$(".board").toggleClass("x o");
});
});
break;


CSS

.x td:hover p {
content:url("images/X.png");
opacity:0.5;
cursor:pointer;
}

.o td:hover p {
content:url("images/O.png");
opacity:0.5;
cursor:pointer;
}

.x .clicked {
content:url("images/X.png");
opacity:1;
}

.o .clicked {
content:url("images/O.png");
opacity:1;
}


HTML

<table class="hidden board" cellspacing="0">
<p class="bigTitle hidden" id="turn">Player Turn</p>
<tbody>
<tr>
<td id="a1"><p></p></td>
<td id="a2"><p></p></td>
<td id="a3"><p></p></td>
</tr>
<tr>
<td id="b1"><p></p></td>
<td id="b2"><p></p></td>
<td id="b3"><p></p></td>
</tr>
<tr>
<td id="c1"><p></p></td>
<td id="c2"><p></p></td>
<td id="c3"><p></p></td>
</tr>
</tbody>
</table>

Answer

Add the function to each individual cell instead of the board, and check within the function if the cell has the clicked class.

$(function(){
    $(".board td").addClass("o");
    $("td").click(function(){
        if( $(this).hasClass('clicked') ) {
            $(this).children("p").addClass("clicked x");
            $(this).toggleClass("x o");
        }
    });
});

Modify the CSS selectors accordingly, for example

td.o:hover p { ...
.x.clicked { ...