I recently delved into the world of JavaScript and decided to challenge myself by creating a TicTacToe game for educational purposes.
If you're curious about what my simple game looks like so far, here's a link to it:
In the game, I prompt the user to choose either "X" or "O" to begin. Initially, I had an "onclick" function embedded in the HTML code, but I learned through research that this is considered poor practice within the industry.
The previous setup with "onclick" directly in the HTML - like
<div class="XO" onclick="userChoice">
- made it straightforward for users to select their choice (X or O) accurately.
However, when I attempted to implement an event listener instead, things got a bit messy. The accuracy of choosing between X and O diminished, as clicking slightly to the left of "X" or to the right of "O" caused unexpected selections. Can anyone provide suggestions? You can view my mini project to see the current implementation.
Below is the JavaScript snippet using an EventListener:
document.addEventListener('DOMContentLoaded', function(domReadyEvent) {
//observe clicks on the document
document.addEventListener('click', function(clickEvent) {
if (clickEvent.target.className.indexOf('X') > -1) {
alert('clicked on X');
//handle click on X
} else if (clickEvent.target.className.indexOf('O') > -1) {
alert('clicked on O');
//handle click on O
}
});
});
I aim to accomplish this strictly within JavaScript. While I have knowledge of HTML, CSS, and more complex languages like C/C++, my experience with JS is fairly limited.
Additionally, I encountered an issue where "O" wasn't being selected. Thanks to some help, the problem turned out to be related to assigning a proper class to "O":
The issue is that you have not set a class for O
It should be: O