Josh Birdwell
Josh Birdwell

Reputation: 745

Tic Tac Toe Game JavaScript

I can not get the button in my javascript to reset to be able to play the game again.

Here is a link to the code: http://jsfiddle.net/jbirdwell/Q3wEZ/

HTML:

<h1>Tic Tac Toe</h1>

<div></div>
<div></div>
<div></div>
<br>
<div></div>
<div></div>
<div></div>
<br>
<div></div>
<div></div>
<div></div>
<br>
<button>New Game</button>

JavaScript:

var x = false;

$(document).ready(function () {
    $('div').click(function () {
        if (!x) {
            $(this).toggleClass('user1');
            x = true;
        } else {
            $(this).toggleClass('user2');
            x = false;
        }
    });

    $('button').click(function () {
        $('div').toggleClass('newgame');
    });    
});

Once the button click event is executed I can not go back to beginning to play again.

Upvotes: 1

Views: 1930

Answers (3)

Dirk
Dirk

Reputation: 2144

Although you change the color of the fields, they still have the "user1" and "user2" classes. So what you'll have to do is reset those.

I have changed your code to make it work, here

$('button').click(function () {
    $("div").removeClass("user1");
    $("div").removeClass("user2");
});

Upvotes: 0

alex
alex

Reputation: 490253

You probably want something more like...

$('button').click(function () {
    $('div').removeClass("user1 user2");
});

Upvotes: 2

eric.itzhak
eric.itzhak

Reputation: 16062

It's because they still have the other classes, try changing it to :

$('button').click(function () {
    $('div').toggleClass('newgame');
    $('div').removeClass('user1 user2');
    x = false;
});

Should work

Upvotes: 2

Related Questions